-
-
Notifications
You must be signed in to change notification settings - Fork 405
Expand file tree
/
Copy pathcontextlib.po
More file actions
1778 lines (1606 loc) · 68.1 KB
/
contextlib.po
File metadata and controls
1778 lines (1606 loc) · 68.1 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
# Copyright (C) 2001-2020, Python Software Foundation
# This file is distributed under the same license as the Python package.
# Maintained by the python-doc-es workteam.
# docs-es@python.org /
# https://mail.python.org/mailman3/lists/docs-es.python.org/
# Check https://github.com/python/python-docs-es/blob/3.8/TRANSLATORS to get
# the list of volunteers
#
msgid ""
msgstr ""
"Project-Id-Version: Python 3.8\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-02-26 18:44-0300\n"
"PO-Revision-Date: 2020-06-24 22:27+0200\n"
"Last-Translator: Cristián Maureira-Fredes <cmaureirafredes@gmail.com>\n"
"Language: es\n"
"Language-Team: python-doc-es\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\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/library/contextlib.rst:2
msgid ""
":mod:`!contextlib` --- Utilities for :keyword:`!with`\\ -statement contexts"
msgstr ""
":mod:`!contextlib` --- Utilidades para declaraciones de contexto :keyword:`!"
"with`"
#: ../Doc/library/contextlib.rst:7
msgid "**Source code:** :source:`Lib/contextlib.py`"
msgstr "**Código fuente:** :source:`Lib/contextlib.py`"
#: ../Doc/library/contextlib.rst:11
msgid ""
"This module provides utilities for common tasks involving the :keyword:"
"`with` statement. For more information see also :ref:`typecontextmanager` "
"and :ref:`context-managers`."
msgstr ""
"Este módulo proporciona utilidades para tareas comunes que involucran la "
"declaración :keyword:`with`. Para obtener más información, consulte también :"
"ref:`typecontextmanager` y :ref:`context-managers`."
#: ../Doc/library/contextlib.rst:17
msgid "Utilities"
msgstr "Utilidades"
#: ../Doc/library/contextlib.rst:19
msgid "Functions and classes provided:"
msgstr "Funciones y clases proporcionadas:"
#: ../Doc/library/contextlib.rst:23
msgid ""
"An :term:`abstract base class` for classes that implement :meth:`object."
"__enter__` and :meth:`object.__exit__`. A default implementation for :meth:"
"`object.__enter__` is provided which returns ``self`` while :meth:`object."
"__exit__` is an abstract method which by default returns ``None``. See also "
"the definition of :ref:`typecontextmanager`."
msgstr ""
"Una :term:`clase base abstracta <abstract base class>` para clases que "
"implementan :meth:`object.__enter__` y :meth:`object.__exit__`. Se "
"proporciona una implementación predeterminada para :meth:`object.__enter__` "
"que retorna ``self`` mientras que :meth:`object.__exit__` es un método "
"abstracto que por defecto retorna ``None``. Véase también la definición de :"
"ref:`typecontextmanager`."
#: ../Doc/library/contextlib.rst:34
msgid ""
"An :term:`abstract base class` for classes that implement :meth:`object."
"__aenter__` and :meth:`object.__aexit__`. A default implementation for :meth:"
"`object.__aenter__` is provided which returns ``self`` while :meth:`object."
"__aexit__` is an abstract method which by default returns ``None``. See also "
"the definition of :ref:`async-context-managers`."
msgstr ""
"Una :term:`clase base abstracta <abstract base class>` para clases que "
"implementan :meth:`object.__aenter__` y :meth:`object.__aexit__`. Se "
"proporciona una implementación predeterminada para :meth:`object.__aenter__` "
"que retorna ``self`` mientras que :meth:`object.__aexit__` es un método "
"abstracto que por defecto retorna ``None``. Véase también la definición de :"
"ref:`async-context-managers`."
#: ../Doc/library/contextlib.rst:46
#, fuzzy
msgid ""
"This function is a :term:`decorator` that can be used to define a factory "
"function for :keyword:`with` statement context managers, without needing to "
"create a class or separate :meth:`~object.__enter__` and :meth:`~object."
"__exit__` methods."
msgstr ""
"Esta función es :term:`decorador` que se puede usar para definir una función "
"de fábrica para gestores de contexto de declaración :keyword:`with`, sin "
"necesidad de crear una clase o separar :meth:`__enter__` y :meth:`__exit__` "
"métodos."
#: ../Doc/library/contextlib.rst:50
#, fuzzy
msgid ""
"While many objects natively support use in with statements, sometimes a "
"resource needs to be managed that isn't a context manager in its own right, "
"and doesn't implement a ``close()`` method for use with ``contextlib."
"closing``."
msgstr ""
"Si bien muchos objetos admiten de forma nativa el uso con declaraciones, a "
"veces es necesario administrar un recurso que no sea un administrador de "
"contexto por sí mismo y no implemente un método ``close()`` para usar con "
"``contextlib.close``"
#: ../Doc/library/contextlib.rst:54
msgid ""
"An abstract example would be the following to ensure correct resource "
"management::"
msgstr ""
"Un ejemplo abstracto sería el siguiente para garantizar la gestión correcta "
"de los recursos::"
#: ../Doc/library/contextlib.rst:57
msgid ""
"from contextlib import contextmanager\n"
"\n"
"@contextmanager\n"
"def managed_resource(*args, **kwds):\n"
" # Code to acquire resource, e.g.:\n"
" resource = acquire_resource(*args, **kwds)\n"
" try:\n"
" yield resource\n"
" finally:\n"
" # Code to release resource, e.g.:\n"
" release_resource(resource)"
msgstr ""
#: ../Doc/library/contextlib.rst:69
msgid "The function can then be used like this::"
msgstr "La función se puede usar así:"
#: ../Doc/library/contextlib.rst:71
msgid ""
">>> with managed_resource(timeout=3600) as resource:\n"
"... # Resource is released at the end of this block,\n"
"... # even if code in the block raises an exception"
msgstr ""
#: ../Doc/library/contextlib.rst:75
msgid ""
"The function being decorated must return a :term:`generator`-iterator when "
"called. This iterator must yield exactly one value, which will be bound to "
"the targets in the :keyword:`with` statement's :keyword:`!as` clause, if any."
msgstr ""
"La función que se está decorando debe retornar un iterador :term:`generador` "
"cuando se llama. Este iterador debe producir exactamente un valor, que "
"estará vinculado a los objetivos en la :keyword:`with` declaración de la "
"cláusula :keyword:`!as`, si existe."
#: ../Doc/library/contextlib.rst:79
msgid ""
"At the point where the generator yields, the block nested in the :keyword:"
"`with` statement is executed. The generator is then resumed after the block "
"is exited. If an unhandled exception occurs in the block, it is reraised "
"inside the generator at the point where the yield occurred. Thus, you can "
"use a :keyword:`try`...\\ :keyword:`except`...\\ :keyword:`finally` "
"statement to trap the error (if any), or ensure that some cleanup takes "
"place. If an exception is trapped merely in order to log it or to perform "
"some action (rather than to suppress it entirely), the generator must "
"reraise that exception. Otherwise the generator context manager will "
"indicate to the :keyword:`!with` statement that the exception has been "
"handled, and execution will resume with the statement immediately following "
"the :keyword:`!with` statement."
msgstr ""
"En el punto donde el generador cede, se ejecuta el bloque anidado en la "
"palabra clave :keyword:`with`. El generador se reanuda luego de salir del "
"bloque. Si se produce una excepción no controlada en el bloque, se vuelve a "
"plantear dentro del generador en el punto donde se produjo el rendimiento. "
"Por lo tanto, puede usar una declaración :keyword:`try`...\\ :keyword:"
"`except`...\\ :keyword:`finally` para atrapar el error (si lo hay), o "
"asegurarse de que se realice una limpieza. Si una excepción queda atrapada "
"simplemente para registrarla o realizar alguna acción (en lugar de "
"suprimirla por completo), el generador debe volver a generar esa excepción. "
"De lo contrario, el administrador de contexto del generador indicará a la "
"palabra clave :keyword:`!with` que se ha manejado la excepción, y la "
"ejecución se reanudará con la declaración inmediatamente siguiente a la "
"palabra clave :keyword:`!with`."
#: ../Doc/library/contextlib.rst:91
msgid ""
":func:`contextmanager` uses :class:`ContextDecorator` so the context "
"managers it creates can be used as decorators as well as in :keyword:`with` "
"statements. When used as a decorator, a new generator instance is implicitly "
"created on each function call (this allows the otherwise \"one-shot\" "
"context managers created by :func:`contextmanager` to meet the requirement "
"that context managers support multiple invocations in order to be used as "
"decorators)."
msgstr ""
":func:`contextmanager` usa :class:`ContextDecorator` para que los gestores "
"de contexto que crea se puedan usar como decoradores, así como en "
"declaraciones :keyword:`with`. Cuando se usa como decorador, se crea "
"implícitamente una nueva instancia de generador en cada llamada de función "
"(esto permite que los gestores de contexto \"de-un-tiro\" creados por :func:"
"`contextmanager` cumplan el requisito de que los gestores de contexto "
"admitan múltiples invocaciones para ser utilizado como decoradores)."
#: ../Doc/library/contextlib.rst:98
msgid "Use of :class:`ContextDecorator`."
msgstr "Uso de :class:`ContextDecorator`."
#: ../Doc/library/contextlib.rst:104
msgid ""
"Similar to :func:`~contextlib.contextmanager`, but creates an :ref:"
"`asynchronous context manager <async-context-managers>`."
msgstr ""
"Similar a :func:`~contextlib.contextmanager`, pero crea un :ref:"
"`administrador de contexto asíncrono <async-context-managers>`."
#: ../Doc/library/contextlib.rst:107
#, fuzzy
msgid ""
"This function is a :term:`decorator` that can be used to define a factory "
"function for :keyword:`async with` statement asynchronous context managers, "
"without needing to create a class or separate :meth:`~object.__aenter__` "
"and :meth:`~object.__aexit__` methods. It must be applied to an :term:"
"`asynchronous generator` function."
msgstr ""
"Esta función es :term:`decorador` que se puede utilizar para definir una "
"función de fábrica para gestores de contexto asíncrono de declaración :"
"keyword:`async with`, sin necesidad de crear una clase o separar :meth:"
"`__aenter__` y métodos :meth:`__aexit__`. Debe aplicarse a una función :term:"
"`asynchronous generator`."
#: ../Doc/library/contextlib.rst:113
msgid "A simple example::"
msgstr "Un ejemplo simple::"
#: ../Doc/library/contextlib.rst:115
msgid ""
"from contextlib import asynccontextmanager\n"
"\n"
"@asynccontextmanager\n"
"async def get_connection():\n"
" conn = await acquire_db_connection()\n"
" try:\n"
" yield conn\n"
" finally:\n"
" await release_db_connection(conn)\n"
"\n"
"async def get_all_users():\n"
" async with get_connection() as conn:\n"
" return conn.query('SELECT ...')"
msgstr ""
#: ../Doc/library/contextlib.rst:131
msgid ""
"Context managers defined with :func:`asynccontextmanager` can be used either "
"as decorators or with :keyword:`async with` statements::"
msgstr ""
"Los administradores de contexto definidos con :func:`asynccontextmanager` se "
"pueden utilizar como decoradores o con declaraciones :keyword:`async with`:"
#: ../Doc/library/contextlib.rst:134
#, python-brace-format
msgid ""
"import time\n"
"from contextlib import asynccontextmanager\n"
"\n"
"@asynccontextmanager\n"
"async def timeit():\n"
" now = time.monotonic()\n"
" try:\n"
" yield\n"
" finally:\n"
" print(f'it took {time.monotonic() - now}s to run')\n"
"\n"
"@timeit()\n"
"async def main():\n"
" # ... async code ..."
msgstr ""
#: ../Doc/library/contextlib.rst:149
msgid ""
"When used as a decorator, a new generator instance is implicitly created on "
"each function call. This allows the otherwise \"one-shot\" context managers "
"created by :func:`asynccontextmanager` to meet the requirement that context "
"managers support multiple invocations in order to be used as decorators."
msgstr ""
"Cuando se utiliza como decorador, se crea implícitamente una nueva instancia "
"de generador en cada llamada de función. Esto permite que los "
"administradores de contexto de otro modo \"únicos\" creados por :func:"
"`asynccontextmanager` cumplan con el requisito de que los administradores de "
"contexto admitan múltiples invocaciones para ser utilizados como decoradores."
#: ../Doc/library/contextlib.rst:154
msgid ""
"Async context managers created with :func:`asynccontextmanager` can be used "
"as decorators."
msgstr ""
"Los administradores de contexto asíncronos creados con :func:"
"`asynccontextmanager` se pueden utilizar como decoradores."
#: ../Doc/library/contextlib.rst:161
msgid ""
"Return a context manager that closes *thing* upon completion of the block. "
"This is basically equivalent to::"
msgstr ""
"retorna un gestor de contexto que cierra *thing* al completar el bloque. "
"Esto es básicamente equivalente a::"
#: ../Doc/library/contextlib.rst:164
msgid ""
"from contextlib import contextmanager\n"
"\n"
"@contextmanager\n"
"def closing(thing):\n"
" try:\n"
" yield thing\n"
" finally:\n"
" thing.close()"
msgstr ""
#: ../Doc/library/contextlib.rst:173
msgid "And lets you write code like this::"
msgstr "Y te permite escribir código como este::"
#: ../Doc/library/contextlib.rst:175
msgid ""
"from contextlib import closing\n"
"from urllib.request import urlopen\n"
"\n"
"with closing(urlopen('https://www.python.org')) as page:\n"
" for line in page:\n"
" print(line)"
msgstr ""
#: ../Doc/library/contextlib.rst:182
msgid ""
"without needing to explicitly close ``page``. Even if an error occurs, "
"``page.close()`` will be called when the :keyword:`with` block is exited."
msgstr ""
"sin necesidad de cerrar explícitamente la ``page``. Incluso si se produce un "
"error, se llamará a ``page.close()`` cuando salga el bloque :keyword:`with`."
#: ../Doc/library/contextlib.rst:187
msgid ""
"Most types managing resources support the :term:`context manager` protocol, "
"which closes *thing* on leaving the :keyword:`with` statement. As such, :"
"func:`!closing` is most useful for third party types that don't support "
"context managers. This example is purely for illustration purposes, as :func:"
"`~urllib.request.urlopen` would normally be used in a context manager."
msgstr ""
#: ../Doc/library/contextlib.rst:196
msgid ""
"Return an async context manager that calls the ``aclose()`` method of "
"*thing* upon completion of the block. This is basically equivalent to::"
msgstr ""
"Retorna un administrador de contexto asíncrono que llama al método "
"``aclose()`` de *thing* una vez completado el bloque. Esto es básicamente "
"equivalente a:"
#: ../Doc/library/contextlib.rst:199
msgid ""
"from contextlib import asynccontextmanager\n"
"\n"
"@asynccontextmanager\n"
"async def aclosing(thing):\n"
" try:\n"
" yield thing\n"
" finally:\n"
" await thing.aclose()"
msgstr ""
#: ../Doc/library/contextlib.rst:208
msgid ""
"Significantly, ``aclosing()`` supports deterministic cleanup of async "
"generators when they happen to exit early by :keyword:`break` or an "
"exception. For example::"
msgstr ""
"Significativamente, ``aclosing()`` admite la limpieza determinista de "
"generadores asincrónicos cuando salen temprano por :keyword:`break` o una "
"excepción. Por ejemplo::"
#: ../Doc/library/contextlib.rst:212
msgid ""
"from contextlib import aclosing\n"
"\n"
"async with aclosing(my_generator()) as values:\n"
" async for value in values:\n"
" if value == 42:\n"
" break"
msgstr ""
#: ../Doc/library/contextlib.rst:219
msgid ""
"This pattern ensures that the generator's async exit code is executed in the "
"same context as its iterations (so that exceptions and context variables "
"work as expected, and the exit code isn't run after the lifetime of some "
"task it depends on)."
msgstr ""
"Este patrón garantiza que el código de salida asíncrono del generador se "
"ejecute en el mismo contexto que sus iteraciones (de modo que las "
"excepciones y las variables de contexto funcionen como se esperaba, y el "
"código de salida no se ejecute después de la vida útil de alguna tarea de la "
"que depende)."
#: ../Doc/library/contextlib.rst:231
msgid ""
"Return a context manager that returns *enter_result* from ``__enter__``, but "
"otherwise does nothing. It is intended to be used as a stand-in for an "
"optional context manager, for example::"
msgstr ""
"retorna un gestor de contexto que retorna *enter_result* de ``__enter__``, "
"pero de lo contrario no hace nada. Está destinado a ser utilizado como un "
"sustituto para un administrador de contexto opcional, por ejemplo:"
#: ../Doc/library/contextlib.rst:235
msgid ""
"def myfunction(arg, ignore_exceptions=False):\n"
" if ignore_exceptions:\n"
" # Use suppress to ignore all exceptions.\n"
" cm = contextlib.suppress(Exception)\n"
" else:\n"
" # Do not ignore any exceptions, cm has no effect.\n"
" cm = contextlib.nullcontext()\n"
" with cm:\n"
" # Do something"
msgstr ""
#: ../Doc/library/contextlib.rst:245
msgid "An example using *enter_result*::"
msgstr "Un ejemplo usando *enter_result*::"
#: ../Doc/library/contextlib.rst:247
msgid ""
"def process_file(file_or_path):\n"
" if isinstance(file_or_path, str):\n"
" # If string, open file\n"
" cm = open(file_or_path)\n"
" else:\n"
" # Caller is responsible for closing file\n"
" cm = nullcontext(file_or_path)\n"
"\n"
" with cm as file:\n"
" # Perform processing on the file"
msgstr ""
#: ../Doc/library/contextlib.rst:258
msgid ""
"It can also be used as a stand-in for :ref:`asynchronous context managers "
"<async-context-managers>`::"
msgstr ""
"También se puede utilizar como sustituto de :ref:`asynchronous context "
"managers <async-context-managers>`:"
#: ../Doc/library/contextlib.rst:261
msgid ""
"async def send_http(session=None):\n"
" if not session:\n"
" # If no http session, create it with aiohttp\n"
" cm = aiohttp.ClientSession()\n"
" else:\n"
" # Caller is responsible for closing the session\n"
" cm = nullcontext(session)\n"
"\n"
" async with cm as session:\n"
" # Send http requests with session"
msgstr ""
#: ../Doc/library/contextlib.rst:274
msgid ":term:`asynchronous context manager` support was added."
msgstr "Se agregó compatibilidad con :term:`asynchronous context manager`."
#: ../Doc/library/contextlib.rst:281
msgid ""
"Return a context manager that suppresses any of the specified exceptions if "
"they occur in the body of a :keyword:`!with` statement and then resumes "
"execution with the first statement following the end of the :keyword:`!with` "
"statement."
msgstr ""
"Retorna un administrador de contexto que suprime cualquiera de las "
"excepciones especificadas si ocurren en el cuerpo de una instrucción :"
"keyword:`!with` y luego reanuda la ejecución con la primera instrucción que "
"sigue al final de la instrucción :keyword:`!with`."
#: ../Doc/library/contextlib.rst:286
msgid ""
"As with any other mechanism that completely suppresses exceptions, this "
"context manager should be used only to cover very specific errors where "
"silently continuing with program execution is known to be the right thing to "
"do."
msgstr ""
"Al igual que con cualquier otro mecanismo que suprima completamente las "
"excepciones, este administrador de contexto debe usarse solo para cubrir "
"errores muy específicos en los que se sabe que continuar silenciosamente con "
"la ejecución del programa es lo correcto."
#: ../Doc/library/contextlib.rst:291
msgid "For example::"
msgstr "Por ejemplo::"
#: ../Doc/library/contextlib.rst:293
msgid ""
"from contextlib import suppress\n"
"\n"
"with suppress(FileNotFoundError):\n"
" os.remove('somefile.tmp')\n"
"\n"
"with suppress(FileNotFoundError):\n"
" os.remove('someotherfile.tmp')"
msgstr ""
#: ../Doc/library/contextlib.rst:301
msgid "This code is equivalent to::"
msgstr "Este código es equivalente a::"
#: ../Doc/library/contextlib.rst:303
msgid ""
"try:\n"
" os.remove('somefile.tmp')\n"
"except FileNotFoundError:\n"
" pass\n"
"\n"
"try:\n"
" os.remove('someotherfile.tmp')\n"
"except FileNotFoundError:\n"
" pass"
msgstr ""
#: ../Doc/library/contextlib.rst:313 ../Doc/library/contextlib.rst:362
#: ../Doc/library/contextlib.rst:372 ../Doc/library/contextlib.rst:389
msgid "This context manager is :ref:`reentrant <reentrant-cms>`."
msgstr "Este gestor de contexto es :ref:`reentrant <reentrant-cms>`."
#: ../Doc/library/contextlib.rst:315
#, fuzzy
msgid ""
"If the code within the :keyword:`!with` block raises a :exc:"
"`BaseExceptionGroup`, suppressed exceptions are removed from the group. Any "
"exceptions of the group which are not suppressed are re-raised in a new "
"group which is created using the original group's :meth:`~BaseExceptionGroup."
"derive` method."
msgstr ""
"Si el código dentro del bloque de :keyword:`!with` lanza una :exc:"
"`ExceptionGroup`, las excepciones suprimidas son retiradas del grupo. Si "
"algunas excepciones en el grupo no están suprimidas, un grupo que las "
"contiene se lanza."
#: ../Doc/library/contextlib.rst:323
#, fuzzy
msgid ""
"``suppress`` now supports suppressing exceptions raised as part of a :exc:"
"`BaseExceptionGroup`."
msgstr ""
"Ahora ``supress`` admite suprimir excepciones lanzadas como parte de un :exc:"
"`ExceptionGroup`."
#: ../Doc/library/contextlib.rst:329
msgid ""
"Context manager for temporarily redirecting :data:`sys.stdout` to another "
"file or file-like object."
msgstr ""
"Administrador de contexto para redirigir temporalmente :data:`sys.stdout` a "
"otro archivo u objeto similar a un archivo."
#: ../Doc/library/contextlib.rst:332
msgid ""
"This tool adds flexibility to existing functions or classes whose output is "
"hardwired to stdout."
msgstr ""
"Esta herramienta agrega flexibilidad a las funciones o clases existentes "
"cuya salida está programada para stdout."
#: ../Doc/library/contextlib.rst:335
msgid ""
"For example, the output of :func:`help` normally is sent to *sys.stdout*. "
"You can capture that output in a string by redirecting the output to an :"
"class:`io.StringIO` object. The replacement stream is returned from the "
"``__enter__`` method and so is available as the target of the :keyword:"
"`with` statement::"
msgstr ""
"Por ejemplo, la salida de :func:`help` normalmente se envía a *sys.stdout*. "
"Puede capturar esa salida en una cadena redirigiendo la salida a un objeto :"
"class:`io.StringIO`. La secuencia de reemplazo se retorna desde el método "
"``__enter__`` y, por lo tanto, está disponible como destino de la "
"declaración :keyword:`with`:"
#: ../Doc/library/contextlib.rst:341
msgid ""
"with redirect_stdout(io.StringIO()) as f:\n"
" help(pow)\n"
"s = f.getvalue()"
msgstr ""
#: ../Doc/library/contextlib.rst:345
msgid ""
"To send the output of :func:`help` to a file on disk, redirect the output to "
"a regular file::"
msgstr ""
"Para enviar la salida de :func:`help` a un archivo en el disco, redirija la "
"salida a un archivo normal::"
#: ../Doc/library/contextlib.rst:348
msgid ""
"with open('help.txt', 'w') as f:\n"
" with redirect_stdout(f):\n"
" help(pow)"
msgstr ""
#: ../Doc/library/contextlib.rst:352
msgid "To send the output of :func:`help` to *sys.stderr*::"
msgstr "Para enviar la salida de :func:`help` a *sys.stderr*::"
#: ../Doc/library/contextlib.rst:354
msgid ""
"with redirect_stdout(sys.stderr):\n"
" help(pow)"
msgstr ""
#: ../Doc/library/contextlib.rst:357
msgid ""
"Note that the global side effect on :data:`sys.stdout` means that this "
"context manager is not suitable for use in library code and most threaded "
"applications. It also has no effect on the output of subprocesses. However, "
"it is still a useful approach for many utility scripts."
msgstr ""
"Tenga en cuenta que el efecto secundario global en :data:`sys.stdout` "
"significa que este administrador de contexto no es adecuado para su uso en "
"el código de la biblioteca y en la mayoría de las aplicaciones con "
"subprocesos. Tampoco tiene efecto en la salida de subprocesos. Sin embargo, "
"sigue siendo un enfoque útil para muchos scripts de utilidad."
#: ../Doc/library/contextlib.rst:369
msgid ""
"Similar to :func:`~contextlib.redirect_stdout` but redirecting :data:`sys."
"stderr` to another file or file-like object."
msgstr ""
"Similar a :func:`~contextlib.redirect_stdout` pero redirigiendo :data:`sys."
"stderr` a otro archivo u objeto similar a un archivo."
#: ../Doc/library/contextlib.rst:379
msgid ""
"Non parallel-safe context manager to change the current working directory. "
"As this changes a global state, the working directory, it is not suitable "
"for use in most threaded or async contexts. It is also not suitable for most "
"non-linear code execution, like generators, where the program execution is "
"temporarily relinquished -- unless explicitly desired, you should not yield "
"when this context manager is active."
msgstr ""
"Administrador de contexto no seguro en paralelo para cambiar el directorio "
"de trabajo actual. Como esto cambia un estado global, el directorio de "
"trabajo, no es adecuado para su uso en la mayoría de los contextos "
"asincrónicos o de subprocesos. Tampoco es adecuado para la mayoría de las "
"ejecuciones de código no lineal, como los generadores, donde la ejecución "
"del programa se abandona temporalmente; a menos que se desee explícitamente, "
"no debe ceder el paso cuando este administrador de contexto está activo."
#: ../Doc/library/contextlib.rst:386
msgid ""
"This is a simple wrapper around :func:`~os.chdir`, it changes the current "
"working directory upon entering and restores the old one on exit."
msgstr ""
"Este es un contenedor simple alrededor de :func:`~os.chdir`, cambia el "
"directorio de trabajo actual al ingresar y restaura el anterior al salir."
#: ../Doc/library/contextlib.rst:396
msgid ""
"A base class that enables a context manager to also be used as a decorator."
msgstr ""
"Una clase base que permite que un administrador de contexto también se use "
"como decorador."
#: ../Doc/library/contextlib.rst:398
msgid ""
"Context managers inheriting from ``ContextDecorator`` have to implement "
"``__enter__`` and ``__exit__`` as normal. ``__exit__`` retains its optional "
"exception handling even when used as a decorator."
msgstr ""
"Los gestores de contexto que heredan de ``ContextDecorator`` tienen que "
"implementar ``__enter__`` y ``__exit__`` de manera normal. ``__exit__`` "
"conserva su manejo opcional de excepciones incluso cuando se usa como "
"decorador."
#: ../Doc/library/contextlib.rst:402
msgid ""
"``ContextDecorator`` is used by :func:`contextmanager`, so you get this "
"functionality automatically."
msgstr ""
"``ContextDecorator`` es utilizado por :func:`contextmanager`, por lo que "
"obtiene esta funcionalidad automáticamente."
#: ../Doc/library/contextlib.rst:405
msgid "Example of ``ContextDecorator``::"
msgstr "Ejemplo de ``ContextDecorator``::"
#: ../Doc/library/contextlib.rst:407
msgid ""
"from contextlib import ContextDecorator\n"
"\n"
"class mycontext(ContextDecorator):\n"
" def __enter__(self):\n"
" print('Starting')\n"
" return self\n"
"\n"
" def __exit__(self, *exc):\n"
" print('Finishing')\n"
" return False"
msgstr ""
#: ../Doc/library/contextlib.rst:418 ../Doc/library/contextlib.rst:490
msgid "The class can then be used like this::"
msgstr "La clase se puede usar así:"
#: ../Doc/library/contextlib.rst:420
msgid ""
">>> @mycontext()\n"
"... def function():\n"
"... print('The bit in the middle')\n"
"...\n"
">>> function()\n"
"Starting\n"
"The bit in the middle\n"
"Finishing\n"
"\n"
">>> with mycontext():\n"
"... print('The bit in the middle')\n"
"...\n"
"Starting\n"
"The bit in the middle\n"
"Finishing"
msgstr ""
#: ../Doc/library/contextlib.rst:436
msgid ""
"This change is just syntactic sugar for any construct of the following form::"
msgstr ""
"Este cambio es solo azúcar sintáctico para cualquier construcción de la "
"siguiente forma:"
#: ../Doc/library/contextlib.rst:438
msgid ""
"def f():\n"
" with cm():\n"
" # Do stuff"
msgstr ""
#: ../Doc/library/contextlib.rst:442
msgid "``ContextDecorator`` lets you instead write::"
msgstr "``ContextDecorator`` le permite escribir en su lugar::"
#: ../Doc/library/contextlib.rst:444
msgid ""
"@cm()\n"
"def f():\n"
" # Do stuff"
msgstr ""
#: ../Doc/library/contextlib.rst:448
msgid ""
"It makes it clear that the ``cm`` applies to the whole function, rather than "
"just a piece of it (and saving an indentation level is nice, too)."
msgstr ""
"Deja en claro que el ``cm`` se aplica a toda la función, en lugar de solo "
"una parte de ella (y guardar un nivel de sangría también es bueno)."
#: ../Doc/library/contextlib.rst:451
msgid ""
"Existing context managers that already have a base class can be extended by "
"using ``ContextDecorator`` as a mixin class::"
msgstr ""
"Los gestores de contexto existentes que ya tienen una clase base pueden "
"ampliarse utilizando ``ContextDecorator`` como una clase mezcla (*mixin*)::"
#: ../Doc/library/contextlib.rst:454
msgid ""
"from contextlib import ContextDecorator\n"
"\n"
"class mycontext(ContextBaseClass, ContextDecorator):\n"
" def __enter__(self):\n"
" return self\n"
"\n"
" def __exit__(self, *exc):\n"
" return False"
msgstr ""
#: ../Doc/library/contextlib.rst:464
msgid ""
"As the decorated function must be able to be called multiple times, the "
"underlying context manager must support use in multiple :keyword:`with` "
"statements. If this is not the case, then the original construct with the "
"explicit :keyword:`!with` statement inside the function should be used."
msgstr ""
"Como la función decorada debe poder llamarse varias veces, el gestor de "
"contexto subyacente debe admitir el uso en múltiples declaraciones :keyword:"
"`with`. Si este no es el caso, se debe utilizar la construcción original con "
"la declaración explícita :keyword:`!with` dentro de la función."
#: ../Doc/library/contextlib.rst:474
msgid ""
"Similar to :class:`ContextDecorator` but only for asynchronous functions."
msgstr ""
"Similar a :class:`ContextDecorator` pero solo para funciones asincrónicas."
#: ../Doc/library/contextlib.rst:476
msgid "Example of ``AsyncContextDecorator``::"
msgstr "Ejemplo de ``AsyncContextDecorator``:"
#: ../Doc/library/contextlib.rst:478
msgid ""
"from asyncio import run\n"
"from contextlib import AsyncContextDecorator\n"
"\n"
"class mycontext(AsyncContextDecorator):\n"
" async def __aenter__(self):\n"
" print('Starting')\n"
" return self\n"
"\n"
" async def __aexit__(self, *exc):\n"
" print('Finishing')\n"
" return False"
msgstr ""
#: ../Doc/library/contextlib.rst:492
msgid ""
">>> @mycontext()\n"
"... async def function():\n"
"... print('The bit in the middle')\n"
"...\n"
">>> run(function())\n"
"Starting\n"
"The bit in the middle\n"
"Finishing\n"
"\n"
">>> async def function():\n"
"... async with mycontext():\n"
"... print('The bit in the middle')\n"
"...\n"
">>> run(function())\n"
"Starting\n"
"The bit in the middle\n"
"Finishing"
msgstr ""
#: ../Doc/library/contextlib.rst:515
msgid ""
"A context manager that is designed to make it easy to programmatically "
"combine other context managers and cleanup functions, especially those that "
"are optional or otherwise driven by input data."
msgstr ""
"Un gestor de contexto que está diseñado para facilitar la combinación "
"programática de otros gestores de contexto y funciones de limpieza, "
"especialmente aquellas que son opcionales o que de otro modo son impulsadas "
"por los datos de entrada."
#: ../Doc/library/contextlib.rst:519
msgid ""
"For example, a set of files may easily be handled in a single with statement "
"as follows::"
msgstr ""
"Por ejemplo, un conjunto de archivos puede manejarse fácilmente en una sola "
"declaración de la siguiente manera:"
#: ../Doc/library/contextlib.rst:522
msgid ""
"with ExitStack() as stack:\n"
" files = [stack.enter_context(open(fname)) for fname in filenames]\n"
" # All opened files will automatically be closed at the end of\n"
" # the with statement, even if attempts to open files later\n"
" # in the list raise an exception"
msgstr ""
#: ../Doc/library/contextlib.rst:528
#, fuzzy
msgid ""
"The :meth:`~object.__enter__` method returns the :class:`ExitStack` "
"instance, and performs no additional operations."
msgstr ""
"El método :meth:`__enter__` retorna la instancia :class:`ExitStack` y no "
"realiza operaciones adicionales."
#: ../Doc/library/contextlib.rst:531
msgid ""
"Each instance maintains a stack of registered callbacks that are called in "
"reverse order when the instance is closed (either explicitly or implicitly "
"at the end of a :keyword:`with` statement). Note that callbacks are *not* "
"invoked implicitly when the context stack instance is garbage collected."
msgstr ""
"Cada instancia mantiene una pila de retrollamadas registradas que se llaman "
"en orden inverso cuando la instancia se cierra (ya sea explícita o "
"implícitamente al final de una instrucción :keyword:`with`). Tenga en cuenta "
"que las retrollamadas *no* se invocan implícitamente cuando la instancia de "
"la pila de contexto se recolecta basura."
#: ../Doc/library/contextlib.rst:536
msgid ""
"This stack model is used so that context managers that acquire their "
"resources in their ``__init__`` method (such as file objects) can be handled "
"correctly."
msgstr ""
"Este modelo de pila se utiliza para que los administradores de contexto que "
"adquieren sus recursos en su método ``__init__`` (como los objetos de "
"archivo) se puedan manejar correctamente."
#: ../Doc/library/contextlib.rst:540
msgid ""
"Since registered callbacks are invoked in the reverse order of registration, "
"this ends up behaving as if multiple nested :keyword:`with` statements had "
"been used with the registered set of callbacks. This even extends to "
"exception handling - if an inner callback suppresses or replaces an "
"exception, then outer callbacks will be passed arguments based on that "
"updated state."
msgstr ""
"Dado que las retrollamadas registradas se invocan en el orden inverso del "
"registro, esto termina comportándose como si se hubieran utilizado múltiples "
"instrucciones anidadas :keyword:`with` con el conjunto registrado de "
"retrollamadas. Esto incluso se extiende al manejo de excepciones: si una "
"retrollamada interna suprime o reemplaza una excepción, las retrollamadas "
"externas se pasarán argumentos basados en ese estado actualizado."
#: ../Doc/library/contextlib.rst:547
msgid ""
"This is a relatively low level API that takes care of the details of "
"correctly unwinding the stack of exit callbacks. It provides a suitable "
"foundation for higher level context managers that manipulate the exit stack "
"in application specific ways."
msgstr ""
"Esta es una API de nivel relativamente bajo que se ocupa de los detalles de "
"desenrollar correctamente la pila de retrollamadas de salida. Proporciona "
"una base adecuada para administradores de contexto de nivel superior que "
"manipulan la pila de salida en formas específicas de la aplicación."
#: ../Doc/library/contextlib.rst:556
#, fuzzy
msgid ""
"Enters a new context manager and adds its :meth:`~object.__exit__` method to "
"the callback stack. The return value is the result of the context manager's "
"own :meth:`~object.__enter__` method."
msgstr ""
"Ingresa a un nuevo administrador de contexto y agrega su método :meth:"
"`__exit__` a la pila de retrollamada. El valor de retorno es el resultado "
"del método propio del administrador de contexto :meth:`__enter__`."
#: ../Doc/library/contextlib.rst:560
msgid ""
"These context managers may suppress exceptions just as they normally would "
"if used directly as part of a :keyword:`with` statement."
msgstr ""
"Estos administradores de contexto pueden suprimir excepciones tal como lo "
"harían normalmente si se usaran directamente como parte de una declaración :"
"keyword:`with`."
#: ../Doc/library/contextlib.rst:563
msgid ""
"Raises :exc:`TypeError` instead of :exc:`AttributeError` if *cm* is not a "
"context manager."
msgstr ""
"Lanza :exc:`TypeError` en lugar de :exc:`AttributeError` si *cm* no es un "
"administrador de contexto."
#: ../Doc/library/contextlib.rst:569
#, fuzzy
msgid ""
"Adds a context manager's :meth:`~object.__exit__` method to the callback "
"stack."
msgstr ""
"Agrega un método de gestor de contexto :meth:`__exit__` a la pila de "
"retrollamada."
#: ../Doc/library/contextlib.rst:571
#, fuzzy
msgid ""
"As ``__enter__`` is *not* invoked, this method can be used to cover part of "
"an :meth:`~object.__enter__` implementation with a context manager's own :"
"meth:`~object.__exit__` method."
msgstr ""
"Como ``__enter__`` *no* se invoca, este método se puede usar para cubrir "
"parte de una implementación :meth:`__enter__` con un método propio del "
"gestor de contexto :meth:`__exit__`."
#: ../Doc/library/contextlib.rst:575
#, fuzzy
msgid ""
"If passed an object that is not a context manager, this method assumes it is "
"a callback with the same signature as a context manager's :meth:`~object."
"__exit__` method and adds it directly to the callback stack."
msgstr ""
"Si se pasa un objeto que no es un administrador de contexto, este método "
"supone que es una retrollamada con la misma firma que el método :meth:"
"`__exit__` de un gestor de contexto y lo agrega directamente a la pila de "
"retrollamada."
#: ../Doc/library/contextlib.rst:579
#, fuzzy
msgid ""
"By returning true values, these callbacks can suppress exceptions the same "
"way context manager :meth:`~object.__exit__` methods can."
msgstr ""
"Al retornar valores verdaderos, estas retrollamadas pueden suprimir "
"excepciones de la misma manera que el gestor de contexto los métodos :meth:"
"`__exit__` pueden hacerlo."
#: ../Doc/library/contextlib.rst:582
msgid ""
"The passed in object is returned from the function, allowing this method to "
"be used as a function decorator."