-
-
Notifications
You must be signed in to change notification settings - Fork 405
Expand file tree
/
Copy pathisolating-extensions.po
More file actions
1202 lines (1068 loc) · 49 KB
/
isolating-extensions.po
File metadata and controls
1202 lines (1068 loc) · 49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SOME DESCRIPTIVE TITLE.
# Copyright (C) 2001-2022, Python Software Foundation
# This file is distributed under the same license as the Python en Español
# package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2022.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Python en Español 3.11\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-02-26 18:44-0300\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=utf-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.18.0\n"
#: ../Doc/howto/isolating-extensions.rst:7
msgid "Isolating Extension Modules"
msgstr "Aislamiento de módulos de extensión"
#: ../Doc/howto/isolating-extensions.rst:-1
msgid "Abstract"
msgstr "Resumen"
#: ../Doc/howto/isolating-extensions.rst:11
msgid ""
"Traditionally, state belonging to Python extension modules was kept in C "
"``static`` variables, which have process-wide scope. This document describes "
"problems of such per-process state and shows a safer way: per-module state."
msgstr ""
"Tradicionalmente, el estado perteneciente a los módulos de extensión de "
"Python se mantuvo en las variables C ``static``, que tienen un alcance de "
"todo el proceso. Este documento describe los problemas de dicho estado por "
"proceso y muestra una forma más segura: el estado por módulo."
#: ../Doc/howto/isolating-extensions.rst:16
msgid ""
"The document also describes how to switch to per-module state where "
"possible. This transition involves allocating space for that state, "
"potentially switching from static types to heap types, and—perhaps most "
"importantly—accessing per-module state from code."
msgstr ""
"El documento también describe cómo cambiar al estado por módulo cuando sea "
"posible. Esta transición implica asignar espacio para ese estado, cambiar "
"potencialmente de tipos estáticos a tipos de montón y, quizás lo más "
"importante, acceder al estado por módulo desde el código."
#: ../Doc/howto/isolating-extensions.rst:23
msgid "Who should read this"
msgstr "¿Quién debería leer esto?"
#: ../Doc/howto/isolating-extensions.rst:25
msgid ""
"This guide is written for maintainers of :ref:`C-API <c-api-index>` "
"extensions who would like to make that extension safer to use in "
"applications where Python itself is used as a library."
msgstr ""
"Esta guía está escrita para los mantenedores de extensiones :ref:`C-API <c-"
"api-index>` que deseen hacer que esa extensión sea más segura para usar en "
"aplicaciones donde Python se usa como biblioteca."
#: ../Doc/howto/isolating-extensions.rst:31
msgid "Background"
msgstr "Trasfondo"
#: ../Doc/howto/isolating-extensions.rst:33
msgid ""
"An *interpreter* is the context in which Python code runs. It contains "
"configuration (e.g. the import path) and runtime state (e.g. the set of "
"imported modules)."
msgstr ""
"Un intérprete (*interpreter*) es el contexto en el que se ejecuta el código "
"de Python. Contiene la configuración (p. ej., la ruta de importación) y el "
"estado de tiempo de ejecución (p. ej., el conjunto de módulos importados)."
#: ../Doc/howto/isolating-extensions.rst:37
msgid ""
"Python supports running multiple interpreters in one process. There are two "
"cases to think about—users may run interpreters:"
msgstr ""
"Python admite la ejecución de varios intérpretes en un solo proceso. Hay dos "
"casos en los que pensar, los usuarios pueden ejecutar intérpretes:"
#: ../Doc/howto/isolating-extensions.rst:40
msgid ""
"in sequence, with several :c:func:`Py_InitializeEx`/:c:func:`Py_FinalizeEx` "
"cycles, and"
msgstr ""
"en secuencia, con varios ciclos :c:func:`Py_InitializeEx`/:c:func:"
"`Py_FinalizeEx`, y"
#: ../Doc/howto/isolating-extensions.rst:42
msgid ""
"in parallel, managing \"sub-interpreters\" using :c:func:"
"`Py_NewInterpreter`/:c:func:`Py_EndInterpreter`."
msgstr ""
"en paralelo, gestionando \"subintérpretes\" mediante :c:func:"
"`Py_NewInterpreter`/:c:func:`Py_EndInterpreter`."
#: ../Doc/howto/isolating-extensions.rst:45
msgid ""
"Both cases (and combinations of them) would be most useful when embedding "
"Python within a library. Libraries generally shouldn't make assumptions "
"about the application that uses them, which include assuming a process-wide "
"\"main Python interpreter\"."
msgstr ""
"Ambos casos (y combinaciones de ellos) serían más útiles al incorporar "
"Python dentro de una biblioteca. Las bibliotecas generalmente no deben hacer "
"suposiciones sobre la aplicación que las usa, lo que incluye asumir un "
"\"intérprete principal de Python\" en todo el proceso."
#: ../Doc/howto/isolating-extensions.rst:50
msgid ""
"Historically, Python extension modules don't handle this use case well. Many "
"extension modules (and even some stdlib modules) use *per-process* global "
"state, because C ``static`` variables are extremely easy to use. Thus, data "
"that should be specific to an interpreter ends up being shared between "
"interpreters. Unless the extension developer is careful, it is very easy to "
"introduce edge cases that lead to crashes when a module is loaded in more "
"than one interpreter in the same process."
msgstr ""
"Históricamente, los módulos de extensión de Python no manejan bien este caso "
"de uso. Muchos módulos de extensión (e incluso algunos módulos stdlib) usan "
"el estado global *por-proceso*, porque las variables C ``static`` son "
"extremadamente fáciles de usar. Así, los datos que deberían ser específicos "
"de un intérprete acaban siendo compartidos entre intérpretes. A menos que el "
"desarrollador de la extensión tenga cuidado, es muy fácil introducir casos "
"extremos que provocan bloqueos cuando un módulo se carga en más de un "
"intérprete en el mismo proceso."
#: ../Doc/howto/isolating-extensions.rst:58
msgid ""
"Unfortunately, *per-interpreter* state is not easy to achieve. Extension "
"authors tend to not keep multiple interpreters in mind when developing, and "
"it is currently cumbersome to test the behavior."
msgstr ""
"Desafortunadamente, el estado *por-intérprete* no es fácil de lograr. Los "
"autores de extensiones tienden a no tener en cuenta múltiples intérpretes "
"cuando desarrollan, y actualmente es engorroso probar el comportamiento."
#: ../Doc/howto/isolating-extensions.rst:63
msgid "Enter Per-Module State"
msgstr "Ingrese al estado por módulo"
#: ../Doc/howto/isolating-extensions.rst:65
#, fuzzy
msgid ""
"Instead of focusing on per-interpreter state, Python's C API is evolving to "
"better support the more granular *per-module* state. This means that C-level "
"data should be attached to a *module object*. Each interpreter creates its "
"own module object, keeping the data separate. For testing the isolation, "
"multiple module objects corresponding to a single extension can even be "
"loaded in a single interpreter."
msgstr ""
"En lugar de centrarse en el estado por intérprete, la API C de Python está "
"evolucionando para admitir mejor el estado *por-módulo* más granular. Esto "
"significa que los datos de nivel C se adjuntan a un *module object*. Cada "
"intérprete crea su propio objeto de módulo, manteniendo los datos separados. "
"Para probar el aislamiento, se pueden cargar varios objetos de módulo "
"correspondientes a una sola extensión en un solo intérprete."
#: ../Doc/howto/isolating-extensions.rst:72
msgid ""
"Per-module state provides an easy way to think about lifetime and resource "
"ownership: the extension module will initialize when a module object is "
"created, and clean up when it's freed. In this regard, a module is just like "
"any other :c:expr:`PyObject *`; there are no \"on interpreter shutdown\" "
"hooks to think—or forget—about."
msgstr ""
"El estado por módulo proporciona una manera fácil de pensar en la vida útil "
"y la propiedad de los recursos: el módulo de extensión se inicializará "
"cuando se cree un objeto de módulo y se limpiará cuando se libere. En este "
"sentido, un módulo es como cualquier otro :c:expr:`PyObject *`; no hay "
"ganchos de \"apagado del intérprete\" para pensar u olvidar."
#: ../Doc/howto/isolating-extensions.rst:78
msgid ""
"Note that there are use cases for different kinds of \"globals\": per-"
"process, per-interpreter, per-thread or per-task state. With per-module "
"state as the default, these are still possible, but you should treat them as "
"exceptional cases: if you need them, you should give them additional care "
"and testing. (Note that this guide does not cover them.)"
msgstr ""
"Tenga en cuenta que hay casos de uso para diferentes tipos de \"globales\": "
"por proceso, por intérprete, por subproceso o por estado de tarea. Con el "
"estado por módulo como predeterminado, estos aún son posibles, pero debe "
"tratarlos como casos excepcionales: si los necesita, debe brindarles "
"atención y pruebas adicionales. (Tenga en cuenta que esta guía no los cubre)."
#: ../Doc/howto/isolating-extensions.rst:87
msgid "Isolated Module Objects"
msgstr "Objetos módulos aislados"
#: ../Doc/howto/isolating-extensions.rst:89
msgid ""
"The key point to keep in mind when developing an extension module is that "
"several module objects can be created from a single shared library. For "
"example:"
msgstr ""
"El punto clave a tener en cuenta al desarrollar un módulo de extensión es "
"que se pueden crear varios objetos de módulo a partir de una única "
"biblioteca compartida. Por ejemplo:"
#: ../Doc/howto/isolating-extensions.rst:93
msgid ""
">>> import sys\n"
">>> import binascii\n"
">>> old_binascii = binascii\n"
">>> del sys.modules['binascii']\n"
">>> import binascii # create a new module object\n"
">>> old_binascii == binascii\n"
"False"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:103
msgid ""
"As a rule of thumb, the two modules should be completely independent. All "
"objects and state specific to the module should be encapsulated within the "
"module object, not shared with other module objects, and cleaned up when the "
"module object is deallocated. Since this just is a rule of thumb, exceptions "
"are possible (see `Managing Global State`_), but they will need more thought "
"and attention to edge cases."
msgstr ""
"Como regla general, los dos módulos deben ser completamente independientes. "
"Todos los objetos y el estado específico del módulo deben encapsularse "
"dentro del objeto del módulo, no compartirse con otros objetos del módulo y "
"limpiarse cuando se desasigna el objeto del módulo. Dado que esto es solo "
"una regla general, las excepciones son posibles (consulte `Managing Global "
"State`_), pero necesitarán más reflexión y atención en los casos extremos."
#: ../Doc/howto/isolating-extensions.rst:111
msgid ""
"While some modules could do with less stringent restrictions, isolated "
"modules make it easier to set clear expectations and guidelines that work "
"across a variety of use cases."
msgstr ""
"Si bien algunos módulos podrían funcionar con restricciones menos estrictas, "
"los módulos aislados facilitan el establecimiento de expectativas y pautas "
"claras que funcionan en una variedad de casos de uso."
#: ../Doc/howto/isolating-extensions.rst:117
msgid "Surprising Edge Cases"
msgstr "Casos extremos sorprendentes"
#: ../Doc/howto/isolating-extensions.rst:119
msgid ""
"Note that isolated modules do create some surprising edge cases. Most "
"notably, each module object will typically not share its classes and "
"exceptions with other similar modules. Continuing from the `example above "
"<Isolated Module Objects_>`__, note that ``old_binascii.Error`` and "
"``binascii.Error`` are separate objects. In the following code, the "
"exception is *not* caught:"
msgstr ""
"Tenga en cuenta que los módulos aislados crean algunos casos extremos "
"sorprendentes. En particular, cada objeto de módulo normalmente no "
"compartirá sus clases y excepciones con otros módulos similares. Continuando "
"con `example above <Isolated Module Objects_>`__, tenga en cuenta que "
"``old_binascii.Error`` y ``binascii.Error`` son objetos separados. En el "
"código siguiente, se detecta la excepción *not*:"
#: ../Doc/howto/isolating-extensions.rst:126
msgid ""
">>> old_binascii.Error == binascii.Error\n"
"False\n"
">>> try:\n"
"... old_binascii.unhexlify(b'qwertyuiop')\n"
"... except binascii.Error:\n"
"... print('boo')\n"
"...\n"
"Traceback (most recent call last):\n"
" File \"<stdin>\", line 2, in <module>\n"
"binascii.Error: Non-hexadecimal digit found"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:139
msgid ""
"This is expected. Notice that pure-Python modules behave the same way: it is "
"a part of how Python works."
msgstr ""
"Esto se espera. Tenga en cuenta que los módulos de Python puro se comportan "
"de la misma manera: es una parte de cómo funciona Python."
#: ../Doc/howto/isolating-extensions.rst:142
msgid ""
"The goal is to make extension modules safe at the C level, not to make hacks "
"behave intuitively. Mutating ``sys.modules`` \"manually\" counts as a hack."
msgstr ""
"El objetivo es hacer que los módulos de extensión sean seguros en el nivel "
"C, no hacer que los piratas informáticos se comporten de manera intuitiva. "
"Mutar ``sys.modules`` \"manualmente\" cuenta como un hack."
#: ../Doc/howto/isolating-extensions.rst:148
msgid "Making Modules Safe with Multiple Interpreters"
msgstr "Cómo hacer que los módulos sean seguros con varios intérpretes"
#: ../Doc/howto/isolating-extensions.rst:152
msgid "Managing Global State"
msgstr "Administrar el estado global"
#: ../Doc/howto/isolating-extensions.rst:154
msgid ""
"Sometimes, the state associated with a Python module is not specific to that "
"module, but to the entire process (or something else \"more global\" than a "
"module). For example:"
msgstr ""
"A veces, el estado asociado con un módulo de Python no es específico de ese "
"módulo, sino de todo el proceso (o algo más \"más global\" que un módulo). "
"Por ejemplo:"
#: ../Doc/howto/isolating-extensions.rst:158
msgid "The ``readline`` module manages *the* terminal."
msgstr "El módulo ``readline`` gestiona *el* terminal."
#: ../Doc/howto/isolating-extensions.rst:159
msgid ""
"A module running on a circuit board wants to control *the* on-board LED."
msgstr ""
"Un módulo que se ejecuta en una placa de circuito quiere controlar *el* LED "
"integrado."
#: ../Doc/howto/isolating-extensions.rst:162
msgid ""
"In these cases, the Python module should provide *access* to the global "
"state, rather than *own* it. If possible, write the module so that multiple "
"copies of it can access the state independently (along with other libraries, "
"whether for Python or other languages). If that is not possible, consider "
"explicit locking."
msgstr ""
"En estos casos, el módulo Python debería proporcionar *acceso* al estado "
"global, en lugar de *poseerlo*. Si es posible, escriba el módulo para que "
"varias copias del mismo puedan acceder al estado de forma independiente "
"(junto con otras bibliotecas, ya sea para Python u otros lenguajes). Si eso "
"no es posible, considere el bloqueo explícito."
#: ../Doc/howto/isolating-extensions.rst:168
#, fuzzy
msgid ""
"If it is necessary to use process-global state, the simplest way to avoid "
"issues with multiple interpreters is to explicitly prevent a module from "
"being loaded more than once per process—see :ref:`isolating-extensions-"
"optout`."
msgstr ""
"Si es necesario usar el estado global del proceso, la forma más sencilla de "
"evitar problemas con varios intérpretes es evitar explícitamente que un "
"módulo se cargue más de una vez por proceso; consulte `Opt-Out: Limiting to "
"One Module Object per Process`_."
#: ../Doc/howto/isolating-extensions.rst:175
msgid "Managing Per-Module State"
msgstr "Administración del estado por módulo"
#: ../Doc/howto/isolating-extensions.rst:177
msgid ""
"To use per-module state, use :ref:`multi-phase extension module "
"initialization <multi-phase-initialization>`. This signals that your module "
"supports multiple interpreters correctly."
msgstr ""
"Para usar el estado por módulo, use :ref:`multi-phase extension module "
"initialization <multi-phase-initialization>`. Esto indica que su módulo "
"admite múltiples intérpretes correctamente."
#: ../Doc/howto/isolating-extensions.rst:181
msgid ""
"Set ``PyModuleDef.m_size`` to a positive number to request that many bytes "
"of storage local to the module. Usually, this will be set to the size of "
"some module-specific ``struct``, which can store all of the module's C-level "
"state. In particular, it is where you should put pointers to classes "
"(including exceptions, but excluding static types) and settings (e.g. "
"``csv``'s :py:data:`~csv.field_size_limit`) which the C code needs to "
"function."
msgstr ""
"Establezca ``PyModuleDef.m_size`` en un número positivo para solicitar "
"tantos bytes de almacenamiento local para el módulo. Por lo general, esto se "
"establecerá en el tamaño de algún ``struct`` específico del módulo, que "
"puede almacenar todo el estado de nivel C del módulo. En particular, es "
"donde debe colocar los punteros a las clases (incluidas las excepciones, "
"pero excluyendo los tipos estáticos) y configuraciones (por ejemplo, :py:"
"data:`~csv.field_size_limit` de ``csv``) que el código C necesita para "
"funcionar."
#: ../Doc/howto/isolating-extensions.rst:190
msgid ""
"Another option is to store state in the module's ``__dict__``, but you must "
"avoid crashing when users modify ``__dict__`` from Python code. This usually "
"means error- and type-checking at the C level, which is easy to get wrong "
"and hard to test sufficiently."
msgstr ""
"Otra opción es almacenar el estado en el ``__dict__`` del módulo, pero debe "
"evitar fallas cuando los usuarios modifican ``__dict__`` desde el código de "
"Python. Esto generalmente significa verificación de errores y tipos en el "
"nivel C, que es fácil equivocarse y difícil de probar lo suficiente."
#: ../Doc/howto/isolating-extensions.rst:195
msgid ""
"However, if module state is not needed in C code, storing it in ``__dict__`` "
"only is a good idea."
msgstr ""
"Sin embargo, si el estado del módulo no es necesario en el código C, "
"almacenarlo solo en ``__dict__`` es una buena idea."
#: ../Doc/howto/isolating-extensions.rst:198
msgid ""
"If the module state includes ``PyObject`` pointers, the module object must "
"hold references to those objects and implement the module-level hooks "
"``m_traverse``, ``m_clear`` and ``m_free``. These work like ``tp_traverse``, "
"``tp_clear`` and ``tp_free`` of a class. Adding them will require some work "
"and make the code longer; this is the price for modules which can be "
"unloaded cleanly."
msgstr ""
"Si el estado del módulo incluye punteros ``PyObject``, el objeto del módulo "
"debe contener referencias a esos objetos e implementar los enlaces de nivel "
"de módulo ``m_traverse``, ``m_clear`` y ``m_free``. Estos funcionan como "
"``tp_traverse``, ``tp_clear`` y ``tp_free`` de una clase. Agregarlos "
"requerirá algo de trabajo y hará que el código sea más largo; este es el "
"precio de los módulos que se pueden descargar limpiamente."
#: ../Doc/howto/isolating-extensions.rst:205
msgid ""
"An example of a module with per-module state is currently available as "
"`xxlimited <https://github.com/python/cpython/blob/master/Modules/xxlimited."
"c>`__; example module initialization shown at the bottom of the file."
msgstr ""
"Un ejemplo de un módulo con estado por módulo está actualmente disponible "
"como `xxlimited <https://github.com/python/cpython/blob/master/Modules/"
"xxlimited.c>`__; ejemplo de inicialización del módulo que se muestra en la "
"parte inferior del archivo."
#: ../Doc/howto/isolating-extensions.rst:213
msgid "Opt-Out: Limiting to One Module Object per Process"
msgstr "Exclusión voluntaria: limitación a un objeto de módulo por proceso"
#: ../Doc/howto/isolating-extensions.rst:215
msgid ""
"A non-negative ``PyModuleDef.m_size`` signals that a module supports "
"multiple interpreters correctly. If this is not yet the case for your "
"module, you can explicitly make your module loadable only once per process. "
"For example::"
msgstr ""
"Un ``PyModuleDef.m_size`` no negativo indica que un módulo admite varios "
"intérpretes correctamente. Si este aún no es el caso de su módulo, puede "
"hacer que su módulo se pueda cargar explícitamente solo una vez por proceso. "
"Por ejemplo::"
#: ../Doc/howto/isolating-extensions.rst:220
msgid ""
"// A process-wide flag\n"
"static int loaded = 0;\n"
"\n"
"// Mutex to provide thread safety (only needed for free-threaded Python)\n"
"static PyMutex modinit_mutex = {0};\n"
"\n"
"static int\n"
"exec_module(PyObject* module)\n"
"{\n"
" PyMutex_Lock(&modinit_mutex);\n"
" if (loaded) {\n"
" PyMutex_Unlock(&modinit_mutex);\n"
" PyErr_SetString(PyExc_ImportError,\n"
" \"cannot load module more than once per process\");\n"
" return -1;\n"
" }\n"
" loaded = 1;\n"
" PyMutex_Unlock(&modinit_mutex);\n"
" // ... rest of initialization\n"
"}"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:242
msgid ""
"If your module's :c:member:`PyModuleDef.m_clear` function is able to prepare "
"for future re-initialization, it should clear the ``loaded`` flag. In this "
"case, your module won't support multiple instances existing *concurrently*, "
"but it will, for example, support being loaded after Python runtime shutdown "
"(:c:func:`Py_FinalizeEx`) and re-initialization (:c:func:`Py_Initialize`)."
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:251
msgid "Module State Access from Functions"
msgstr "Acceso al estado del módulo desde las funciones"
#: ../Doc/howto/isolating-extensions.rst:253
msgid ""
"Accessing the state from module-level functions is straightforward. "
"Functions get the module object as their first argument; for extracting the "
"state, you can use ``PyModule_GetState``::"
msgstr ""
"Acceder al estado desde funciones a nivel de módulo es sencillo. Las "
"funciones obtienen el objeto del módulo como su primer argumento; para "
"extraer el estado, puede usar ``PyModule_GetState``::"
#: ../Doc/howto/isolating-extensions.rst:257
msgid ""
"static PyObject *\n"
"func(PyObject *module, PyObject *args)\n"
"{\n"
" my_struct *state = (my_struct*)PyModule_GetState(module);\n"
" if (state == NULL) {\n"
" return NULL;\n"
" }\n"
" // ... rest of logic\n"
"}"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:268
msgid ""
"``PyModule_GetState`` may return ``NULL`` without setting an exception if "
"there is no module state, i.e. ``PyModuleDef.m_size`` was zero. In your own "
"module, you're in control of ``m_size``, so this is easy to prevent."
msgstr ""
"``PyModule_GetState`` puede retornar ``NULL`` sin establecer una excepción "
"si no hay un estado de módulo, es decir, ``PyModuleDef.m_size`` era cero. En "
"su propio módulo, tiene el control de ``m_size``, por lo que es fácil de "
"evitar."
#: ../Doc/howto/isolating-extensions.rst:275
msgid "Heap Types"
msgstr "Tipos Heap"
#: ../Doc/howto/isolating-extensions.rst:277
msgid ""
"Traditionally, types defined in C code are *static*; that is, ``static "
"PyTypeObject`` structures defined directly in code and initialized using "
"``PyType_Ready()``."
msgstr ""
"Tradicionalmente, los tipos definidos en código C son *estáticos*; es decir, "
"estructuras ``static PyTypeObject`` definidas directamente en el código e "
"inicializadas mediante ``PyType_Ready()``."
#: ../Doc/howto/isolating-extensions.rst:281
msgid ""
"Such types are necessarily shared across the process. Sharing them between "
"module objects requires paying attention to any state they own or access. To "
"limit the possible issues, static types are immutable at the Python level: "
"for example, you can't set ``str.myattribute = 123``."
msgstr ""
"Tales tipos son necesariamente compartidos a lo largo del proceso. "
"Compartirlos entre objetos de módulo requiere prestar atención a cualquier "
"estado que posean o al que accedan. Para limitar los posibles problemas, los "
"tipos estáticos son inmutables en el nivel de Python: por ejemplo, no puede "
"configurar ``str.myattribute = 123``."
#: ../Doc/howto/isolating-extensions.rst:287
msgid ""
"Sharing truly immutable objects between interpreters is fine, as long as "
"they don't provide access to mutable objects. However, in CPython, every "
"Python object has a mutable implementation detail: the reference count. "
"Changes to the refcount are guarded by the GIL. Thus, code that shares any "
"Python objects across interpreters implicitly depends on CPython's current, "
"process-wide GIL."
msgstr ""
"Compartir objetos verdaderamente inmutables entre intérpretes está bien, "
"siempre que no proporcionen acceso a objetos mutables. Sin embargo, en "
"CPython, cada objeto de Python tiene un detalle de implementación mutable: "
"el recuento de referencias. Los cambios en el refcount están protegidos por "
"el GIL. Por lo tanto, el código que comparte cualquier objeto de Python "
"entre intérpretes depende implícitamente del GIL actual de todo el proceso "
"de CPython."
#: ../Doc/howto/isolating-extensions.rst:294
msgid ""
"Because they are immutable and process-global, static types cannot access "
"\"their\" module state. If any method of such a type requires access to "
"module state, the type must be converted to a *heap-allocated type*, or "
"*heap type* for short. These correspond more closely to classes created by "
"Python's ``class`` statement."
msgstr ""
"Debido a que son inmutables y globales de proceso, los tipos estáticos no "
"pueden acceder a \"su\" estado de módulo. Si algún método de este tipo "
"requiere acceso al estado del módulo, el tipo debe convertirse a *tipo "
"almacenado en memoria dinámica (heap)* o *tipo heap* para abreviar. Estos se "
"corresponden más estrechamente con las clases creadas por la instrucción "
"``class`` de Python."
#: ../Doc/howto/isolating-extensions.rst:301
msgid "For new modules, using heap types by default is a good rule of thumb."
msgstr ""
"Para los módulos nuevos, usar tipos heap de forma predeterminada es una "
"buena regla general."
#: ../Doc/howto/isolating-extensions.rst:305
msgid "Changing Static Types to Heap Types"
msgstr "Cambio de tipos estáticos a tipos heap"
#: ../Doc/howto/isolating-extensions.rst:307
msgid ""
"Static types can be converted to heap types, but note that the heap type API "
"was not designed for \"lossless\" conversion from static types—that is, "
"creating a type that works exactly like a given static type. So, when "
"rewriting the class definition in a new API, you are likely to "
"unintentionally change a few details (e.g. pickleability or inherited "
"slots). Always test the details that are important to you."
msgstr ""
"Los tipos estáticos se pueden convertir en tipos heap, pero tenga en cuenta "
"que la API de tipo heap no se diseñó para la conversión \"sin pérdidas\" de "
"tipos estáticos, es decir, para crear un tipo que funcione exactamente como "
"un tipo estático determinado. Por lo tanto, al reescribir la definición de "
"clase en una nueva API, es probable que cambie sin querer algunos detalles "
"(por ejemplo, capacidad de selección o espacios heredados). Siempre pruebe "
"los detalles que son importantes para usted."
#: ../Doc/howto/isolating-extensions.rst:316
msgid ""
"Watch out for the following two points in particular (but note that this is "
"not a comprehensive list):"
msgstr ""
"Tenga cuidado con los siguientes dos puntos en particular (pero tenga en "
"cuenta que esta no es una lista completa):"
#: ../Doc/howto/isolating-extensions.rst:319
#, fuzzy
msgid ""
"Unlike static types, heap type objects are mutable by default. Use the :c:"
"macro:`Py_TPFLAGS_IMMUTABLETYPE` flag to prevent mutability."
msgstr ""
"A diferencia de los tipos estáticos, los objetos de tipo heap son mutables "
"de forma predeterminada. Utilice el indicador :c:data:"
"`Py_TPFLAGS_IMMUTABLETYPE` para evitar la mutabilidad."
#: ../Doc/howto/isolating-extensions.rst:321
#, fuzzy
msgid ""
"Heap types inherit :c:member:`~PyTypeObject.tp_new` by default, so it may "
"become possible to instantiate them from Python code. You can prevent this "
"with the :c:macro:`Py_TPFLAGS_DISALLOW_INSTANTIATION` flag."
msgstr ""
"Los tipos heap heredan :c:member:`~PyTypeObject.tp_new` de forma "
"predeterminada, por lo que es posible crear instancias de ellos desde el "
"código de Python. Puede evitar esto con el indicador :c:data:"
"`Py_TPFLAGS_DISALLOW_INSTANTIATION`."
#: ../Doc/howto/isolating-extensions.rst:327
msgid "Defining Heap Types"
msgstr "Definición de tipos heap"
#: ../Doc/howto/isolating-extensions.rst:329
msgid ""
"Heap types can be created by filling a :c:struct:`PyType_Spec` structure, a "
"description or \"blueprint\" of a class, and calling :c:func:"
"`PyType_FromModuleAndSpec` to construct a new class object."
msgstr ""
"Los tipos heap se pueden crear completando una estructura :c:struct:"
"`PyType_Spec`, una descripción o \"modelo\" de una clase y llamando a :c:"
"func:`PyType_FromModuleAndSpec` para construir un nuevo objeto de clase."
#: ../Doc/howto/isolating-extensions.rst:334
msgid ""
"Other functions, like :c:func:`PyType_FromSpec`, can also create heap types, "
"but :c:func:`PyType_FromModuleAndSpec` associates the module with the class, "
"allowing access to the module state from methods."
msgstr ""
"Otras funciones, como :c:func:`PyType_FromSpec`, también pueden crear tipos "
"heap, pero :c:func:`PyType_FromModuleAndSpec` asocia el módulo con la clase, "
"lo que permite el acceso al estado del módulo desde los métodos."
#: ../Doc/howto/isolating-extensions.rst:338
msgid ""
"The class should generally be stored in *both* the module state (for safe "
"access from C) and the module's ``__dict__`` (for access from Python code)."
msgstr ""
"La clase generalmente debe almacenarse en *ambos*, el estado del módulo "
"(para acceso seguro desde C) y el ``__dict__`` del módulo (para acceso desde "
"código Python)."
#: ../Doc/howto/isolating-extensions.rst:344
msgid "Garbage-Collection Protocol"
msgstr "Protocolo de recolección de basura"
#: ../Doc/howto/isolating-extensions.rst:346
msgid ""
"Instances of heap types hold a reference to their type. This ensures that "
"the type isn't destroyed before all its instances are, but may result in "
"reference cycles that need to be broken by the garbage collector."
msgstr ""
"Las instancias de tipos heap contienen una referencia a su tipo. Esto "
"garantiza que el tipo no se destruya antes de que se destruyan todas sus "
"instancias, pero puede generar ciclos de referencia que el recolector de "
"elementos no utilizados debe interrumpir."
#: ../Doc/howto/isolating-extensions.rst:351
msgid ""
"To avoid memory leaks, instances of heap types must implement the garbage "
"collection protocol. That is, heap types should:"
msgstr ""
"Para evitar pérdidas de memoria, las instancias de los tipos heap deben "
"implementar el protocolo de recolección de elementos no utilizados. Es "
"decir, los tipos heap deben:"
#: ../Doc/howto/isolating-extensions.rst:355
#, fuzzy
msgid "Have the :c:macro:`Py_TPFLAGS_HAVE_GC` flag."
msgstr "Tener la bandera :c:data:`Py_TPFLAGS_HAVE_GC`."
#: ../Doc/howto/isolating-extensions.rst:356
#, fuzzy
msgid ""
"Define a traverse function using ``Py_tp_traverse``, which visits the type "
"(e.g. using ``Py_VISIT(Py_TYPE(self))``)."
msgstr ""
"Defina una función transversal usando ``Py_tp_traverse``, que visita el tipo "
"(por ejemplo, usando :c:expr:`Py_VISIT(Py_TYPE(self))`)."
#: ../Doc/howto/isolating-extensions.rst:359
#, fuzzy
msgid ""
"Please refer to the documentation of :c:macro:`Py_TPFLAGS_HAVE_GC` and :c:"
"member:`~PyTypeObject.tp_traverse` for additional considerations."
msgstr ""
"Consulte el :ref:`the documentation <type-structs>` de :c:data:"
"`Py_TPFLAGS_HAVE_GC` y :c:member:`~PyTypeObject.tp_traverse` para obtener "
"consideraciones adicionales."
#: ../Doc/howto/isolating-extensions.rst:363
msgid ""
"The API for defining heap types grew organically, leaving it somewhat "
"awkward to use in its current state. The following sections will guide you "
"through common issues."
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:369
msgid "``tp_traverse`` in Python 3.8 and lower"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:371
msgid ""
"The requirement to visit the type from ``tp_traverse`` was added in Python "
"3.9. If you support Python 3.8 and lower, the traverse function must *not* "
"visit the type, so it must be more complicated::"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:375
msgid ""
"static int my_traverse(PyObject *self, visitproc visit, void *arg)\n"
"{\n"
" if (Py_Version >= 0x03090000) {\n"
" Py_VISIT(Py_TYPE(self));\n"
" }\n"
" return 0;\n"
"}"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:383
msgid ""
"Unfortunately, :c:data:`Py_Version` was only added in Python 3.11. As a "
"replacement, use:"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:386
msgid ":c:macro:`PY_VERSION_HEX`, if not using the stable ABI, or"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:387
msgid ""
":py:data:`sys.version_info` (via :c:func:`PySys_GetObject` and :c:func:"
"`PyArg_ParseTuple`)."
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:392
msgid "Delegating ``tp_traverse``"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:394
#, fuzzy
msgid ""
"If your traverse function delegates to the :c:member:`~PyTypeObject."
"tp_traverse` of its base class (or another type), ensure that "
"``Py_TYPE(self)`` is visited only once. Note that only heap type are "
"expected to visit the type in ``tp_traverse``."
msgstr ""
"Si su función transversal delega al ``tp_traverse`` de su clase base (u otro "
"tipo), asegúrese de que ``Py_TYPE(self)`` se visite solo una vez. Tenga en "
"cuenta que solo se espera que el tipo de montón visite el tipo en "
"``tp_traverse``."
#: ../Doc/howto/isolating-extensions.rst:399
msgid "For example, if your traverse function includes::"
msgstr "Por ejemplo, si su función poligonal incluye:"
#: ../Doc/howto/isolating-extensions.rst:401
msgid "base->tp_traverse(self, visit, arg)"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:403
msgid "...and ``base`` may be a static type, then it should also include::"
msgstr ""
"...y ``base`` puede ser un tipo estático, entonces también debe incluir:"
#: ../Doc/howto/isolating-extensions.rst:405
msgid ""
"if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) {\n"
" // a heap type's tp_traverse already visited Py_TYPE(self)\n"
"} else {\n"
" if (Py_Version >= 0x03090000) {\n"
" Py_VISIT(Py_TYPE(self));\n"
" }\n"
"}"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:413
#, fuzzy
msgid ""
"It is not necessary to handle the type's reference count in :c:member:"
"`~PyTypeObject.tp_new` and :c:member:`~PyTypeObject.tp_clear`."
msgstr ""
"No es necesario manejar el recuento de referencias del tipo en ``tp_new`` y "
"``tp_clear``."
#: ../Doc/howto/isolating-extensions.rst:418
msgid "Defining ``tp_dealloc``"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:420
msgid ""
"If your type has a custom :c:member:`~PyTypeObject.tp_dealloc` function, it "
"needs to:"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:423
msgid ""
"call :c:func:`PyObject_GC_UnTrack` before any fields are invalidated, and"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:424
msgid "decrement the reference count of the type."
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:426
msgid ""
"To keep the type valid while ``tp_free`` is called, the type's refcount "
"needs to be decremented *after* the instance is deallocated. For example::"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:429
#, python-brace-format
msgid ""
"static void my_dealloc(PyObject *self)\n"
"{\n"
" PyObject_GC_UnTrack(self);\n"
" ...\n"
" PyTypeObject *type = Py_TYPE(self);\n"
" type->tp_free(self);\n"
" Py_DECREF(type);\n"
"}"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:438
msgid ""
"The default ``tp_dealloc`` function does this, so if your type does *not* "
"override ``tp_dealloc`` you don't need to add it."
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:444
msgid "Not overriding ``tp_free``"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:446
msgid ""
"The :c:member:`~PyTypeObject.tp_free` slot of a heap type must be set to :c:"
"func:`PyObject_GC_Del`. This is the default; do not override it."
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:452
msgid "Avoiding ``PyObject_New``"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:454
msgid "GC-tracked objects need to be allocated using GC-aware functions."
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:456
msgid "If you use :c:func:`PyObject_New` or :c:func:`PyObject_NewVar`:"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:458
msgid ""
"Get and call type's :c:member:`~PyTypeObject.tp_alloc` slot, if possible. "
"That is, replace ``TYPE *o = PyObject_New(TYPE, typeobj)`` with::"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:461
msgid "TYPE *o = typeobj->tp_alloc(typeobj, 0);"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:463
msgid ""
"Replace ``o = PyObject_NewVar(TYPE, typeobj, size)`` with the same, but use "
"size instead of the 0."
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:466
msgid ""
"If the above is not possible (e.g. inside a custom ``tp_alloc``), call :c:"
"func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`::"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:469
msgid ""
"TYPE *o = PyObject_GC_New(TYPE, typeobj);\n"
"\n"
"TYPE *o = PyObject_GC_NewVar(TYPE, typeobj, size);"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:475
msgid "Module State Access from Classes"
msgstr "Acceso al estado del módulo desde las clases"
#: ../Doc/howto/isolating-extensions.rst:477
msgid ""
"If you have a type object defined with :c:func:`PyType_FromModuleAndSpec`, "
"you can call :c:func:`PyType_GetModule` to get the associated module, and "
"then :c:func:`PyModule_GetState` to get the module's state."
msgstr ""
"Si tiene un objeto de tipo definido con :c:func:`PyType_FromModuleAndSpec`, "
"puede llamar a :c:func:`PyType_GetModule` para obtener el módulo asociado y "
"luego a :c:func:`PyModule_GetState` para obtener el estado del módulo."
#: ../Doc/howto/isolating-extensions.rst:481
msgid ""
"To save a some tedious error-handling boilerplate code, you can combine "
"these two steps with :c:func:`PyType_GetModuleState`, resulting in::"
msgstr ""
"Para ahorrar un tedioso código repetitivo de manejo de errores, puede "
"combinar estos dos pasos con :c:func:`PyType_GetModuleState`, lo que da como "
"resultado:"
#: ../Doc/howto/isolating-extensions.rst:484
#, python-brace-format
msgid ""
"my_struct *state = (my_struct*)PyType_GetModuleState(type);\n"
"if (state == NULL) {\n"
" return NULL;\n"
"}"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:491
msgid "Module State Access from Regular Methods"
msgstr "Acceso al estado del módulo desde métodos regulares"
#: ../Doc/howto/isolating-extensions.rst:493
msgid ""
"Accessing the module-level state from methods of a class is somewhat more "
"complicated, but is possible thanks to API introduced in Python 3.9. To get "
"the state, you need to first get the *defining class*, and then get the "
"module state from it."
msgstr ""
"Acceder al estado de nivel de módulo desde los métodos de una clase es algo "
"más complicado, pero es posible gracias a la API introducida en Python 3.9. "
"Para obtener el estado, primero debe obtener la *clase de definición* y "
"luego obtener el estado del módulo."
#: ../Doc/howto/isolating-extensions.rst:498
msgid ""
"The largest roadblock is getting *the class a method was defined in*, or "
"that method's \"defining class\" for short. The defining class can have a "
"reference to the module it is part of."
msgstr ""
"El obstáculo más grande es obtener *la clase en la que se definió un "
"método*, o la \"clase de definición\" de ese método para abreviar. La clase "
"de definición puede tener una referencia al módulo del que forma parte."
#: ../Doc/howto/isolating-extensions.rst:502
#, fuzzy
msgid ""
"Do not confuse the defining class with ``Py_TYPE(self)``. If the method is "
"called on a *subclass* of your type, ``Py_TYPE(self)`` will refer to that "
"subclass, which may be defined in different module than yours."
msgstr ""
"No confunda la clase de definición con :c:expr:`Py_TYPE(self)`. Si se llama "
"al método en una *subclase* de su tipo, ``Py_TYPE(self)`` se referirá a esa "
"subclase, que puede estar definida en un módulo diferente al suyo."
#: ../Doc/howto/isolating-extensions.rst:507
msgid ""
"The following Python code can illustrate the concept. ``Base."
"get_defining_class`` returns ``Base`` even if ``type(self) == Sub``:"
msgstr ""
"El siguiente código de Python puede ilustrar el concepto. ``Base."
"get_defining_class`` retorna ``Base`` incluso si ``type(self) == Sub``:"
#: ../Doc/howto/isolating-extensions.rst:511
msgid ""
"class Base:\n"
" def get_type_of_self(self):\n"
" return type(self)\n"
"\n"
" def get_defining_class(self):\n"
" return __class__\n"
"\n"
"class Sub(Base):\n"
" pass"
msgstr ""
#: ../Doc/howto/isolating-extensions.rst:523
#, fuzzy
msgid ""
"For a method to get its \"defining class\", it must use the :ref:"
"`METH_METHOD | METH_FASTCALL | METH_KEYWORDS <METH_METHOD-METH_FASTCALL-"