# 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: 2022-10-25 19:47+0200\n" "PO-Revision-Date: 2020-06-24 22:27+0200\n" "Last-Translator: Cristián Maureira-Fredes \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.10.3\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 ` para clases que " "implementan :meth:`object.__aenter__` 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 ` 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 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:`__enter__` and :meth:`__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 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:69 msgid "The function can then be used like this::" 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 `." msgstr "" "Similar a :func:`~contextlib.contextmanager`, pero crea un :ref:" "`administrador de contexto asíncrono `." #: ../Doc/library/contextlib.rst:107 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:`__aenter__` and :meth:" "`__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: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: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:173 msgid "And lets you write code like this::" msgstr "Y te permite escribir código como este::" #: ../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:188 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:200 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:211 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:223 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:237 msgid "An example using *enter_result*::" msgstr "Un ejemplo usando *enter_result*::" #: ../Doc/library/contextlib.rst:250 msgid "" "It can also be used as a stand-in for :ref:`asynchronous context managers " "`::" msgstr "" "También se puede utilizar como sustituto de :ref:`asynchronous context " "managers `:" #: ../Doc/library/contextlib.rst:266 msgid ":term:`asynchronous context manager` support was added." msgstr "Se agregó compatibilidad con :term:`asynchronous context manager`." #: ../Doc/library/contextlib.rst:273 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:278 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:283 msgid "For example::" msgstr "Por ejemplo::" #: ../Doc/library/contextlib.rst:293 msgid "This code is equivalent to::" msgstr "Este código es equivalente a::" #: ../Doc/library/contextlib.rst:305 ../Doc/library/contextlib.rst:345 #: ../Doc/library/contextlib.rst:355 ../Doc/library/contextlib.rst:372 msgid "This context manager is :ref:`reentrant `." msgstr "Este gestor de contexto es :ref:`reentrant `." #: ../Doc/library/contextlib.rst:312 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:315 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:318 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:328 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:335 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:340 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:352 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:362 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 "" #: ../Doc/library/contextlib.rst:369 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 "" #: ../Doc/library/contextlib.rst:379 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:381 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:385 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:388 msgid "Example of ``ContextDecorator``::" msgstr "Ejemplo de ``ContextDecorator``::" #: ../Doc/library/contextlib.rst:401 ../Doc/library/contextlib.rst:473 msgid "The class can then be used like this::" msgstr "" #: ../Doc/library/contextlib.rst:419 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:425 msgid "``ContextDecorator`` lets you instead write::" msgstr "``ContextDecorator`` le permite escribir en su lugar::" #: ../Doc/library/contextlib.rst:431 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:434 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:447 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:457 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:459 msgid "Example of ``AsyncContextDecorator``::" msgstr "Ejemplo de ``AsyncContextDecorator``:" #: ../Doc/library/contextlib.rst:498 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:502 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:511 msgid "" "The :meth:`__enter__` method returns the :class:`ExitStack` instance, and " "performs no additional operations." msgstr "" #: ../Doc/library/contextlib.rst:514 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:519 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:523 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:530 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:539 msgid "" "Enters a new context manager and adds its :meth:`__exit__` method to the " "callback stack. The return value is the result of the context manager's own :" "meth:`__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:543 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:546 msgid "" "Raises :exc:`TypeError` instead of :exc:`AttributeError` if *cm* is not a " "context manager." msgstr "" #: ../Doc/library/contextlib.rst:552 msgid "Adds a context manager's :meth:`__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:554 msgid "" "As ``__enter__`` is *not* invoked, this method can be used to cover part of " "an :meth:`__enter__` implementation with a context manager's own :meth:" "`__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:558 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:`__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:562 msgid "" "By returning true values, these callbacks can suppress exceptions the same " "way context manager :meth:`__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:565 msgid "" "The passed in object is returned from the function, allowing this method to " "be used as a function decorator." msgstr "" "El objeto pasado se retorna desde la función, lo que permite que este método " "se use como decorador de funciones." #: ../Doc/library/contextlib.rst:570 msgid "" "Accepts an arbitrary callback function and arguments and adds it to the " "callback stack." msgstr "" "Acepta una función de retrollamada arbitraria y argumentos y la agrega a la " "pila de retrollamada." #: ../Doc/library/contextlib.rst:573 msgid "" "Unlike the other methods, callbacks added this way cannot suppress " "exceptions (as they are never passed the exception details)." msgstr "" "A diferencia de los otros métodos, las retrollamadas agregadas de esta " "manera no pueden suprimir excepciones (ya que nunca se pasan los detalles de " "excepción)." #: ../Doc/library/contextlib.rst:576 msgid "" "The passed in callback is returned from the function, allowing this method " "to be used as a function decorator." msgstr "" "La retrollamada pasada se retorna desde la función, lo que permite que este " "método se use como decorador de funciones." #: ../Doc/library/contextlib.rst:581 msgid "" "Transfers the callback stack to a fresh :class:`ExitStack` instance and " "returns it. No callbacks are invoked by this operation - instead, they will " "now be invoked when the new stack is closed (either explicitly or implicitly " "at the end of a :keyword:`with` statement)." msgstr "" "Transfiere la pila de retrollamada a una instancia fresca :class:`ExitStack` " "y la retorna. Esta operación no invoca retrollamadas; en cambio, ahora se " "invocarán cuando se cierre la nueva pila (ya sea explícita o implícitamente " "al final de una instrucción :keyword:`with`)." #: ../Doc/library/contextlib.rst:586 msgid "" "For example, a group of files can be opened as an \"all or nothing\" " "operation as follows::" msgstr "" "Por ejemplo, un grupo de archivos se puede abrir como una operación de " "\"todo o nada\" de la siguiente manera:" #: ../Doc/library/contextlib.rst:600 msgid "" "Immediately unwinds the callback stack, invoking callbacks in the reverse " "order of registration. For any context managers and exit callbacks " "registered, the arguments passed in will indicate that no exception occurred." msgstr "" "Inmediatamente desenrolla la pila de retrollamada, invocando retrollamadas " "en el orden inverso de registro. Para los administradores de contexto y las " "retrollamadas de salida registradas, los argumentos pasados indicarán que no " "se produjo ninguna excepción." #: ../Doc/library/contextlib.rst:607 msgid "" "An :ref:`asynchronous context manager `, similar to :" "class:`ExitStack`, that supports combining both synchronous and asynchronous " "context managers, as well as having coroutines for cleanup logic." msgstr "" "Un :ref:`gestor de contexto asíncrono `, similar a :" "class:`ExitStack`, que admite la combinación de gestores de contexto " "síncrono y asíncrono, además de tener rutinas para la lógica de limpieza." #: ../Doc/library/contextlib.rst:612 msgid "" "The :meth:`close` method is not implemented, :meth:`aclose` must be used " "instead." msgstr "" "El método :meth:`close` no está implementado, :meth:`aclose` debe usarse en " "su lugar." #: ../Doc/library/contextlib.rst:617 msgid "" "Similar to :meth:`enter_context` but expects an asynchronous context manager." msgstr "" "Similar a :meth:`enter_context` pero espera un administrador de contexto " "asíncrono." #: ../Doc/library/contextlib.rst:620 msgid "" "Raises :exc:`TypeError` instead of :exc:`AttributeError` if *cm* is not an " "asynchronous context manager." msgstr "" #: ../Doc/library/contextlib.rst:626 msgid "" "Similar to :meth:`push` but expects either an asynchronous context manager " "or a coroutine function." msgstr "" "Similar a :meth:`push` pero espera un gestor de contexto asíncrono o una " "función de rutina." #: ../Doc/library/contextlib.rst:631 msgid "Similar to :meth:`callback` but expects a coroutine function." msgstr "Similar a :meth:`callback` pero espera una función de rutina." #: ../Doc/library/contextlib.rst:635 msgid "Similar to :meth:`close` but properly handles awaitables." msgstr "" "Similar a :meth:`close` pero maneja adecuadamente los objetos de espera." #: ../Doc/library/contextlib.rst:637 msgid "Continuing the example for :func:`asynccontextmanager`::" msgstr "Continuando con el ejemplo para :func:`asynccontextmanager`::" #: ../Doc/library/contextlib.rst:649 msgid "Examples and Recipes" msgstr "Ejemplos y recetas" #: ../Doc/library/contextlib.rst:651 msgid "" "This section describes some examples and recipes for making effective use of " "the tools provided by :mod:`contextlib`." msgstr "" "Esta sección describe algunos ejemplos y recetas para hacer un uso efectivo " "de las herramientas proporcionadas por :mod:`contextlib`." #: ../Doc/library/contextlib.rst:656 msgid "Supporting a variable number of context managers" msgstr "Apoyando un número variable de gestores de contexto" #: ../Doc/library/contextlib.rst:658 msgid "" "The primary use case for :class:`ExitStack` is the one given in the class " "documentation: supporting a variable number of context managers and other " "cleanup operations in a single :keyword:`with` statement. The variability " "may come from the number of context managers needed being driven by user " "input (such as opening a user specified collection of files), or from some " "of the context managers being optional::" msgstr "" "El caso de uso principal para :class:`ExitStack` es el que se proporciona en " "la documentación de la clase: admite un número variable de gestores de " "contexto y otras operaciones de limpieza en una sola :keyword:`with`. La " "variabilidad puede provenir de la cantidad de gestores de contexto que " "necesitan ser impulsados por la entrada del usuario (como abrir una " "colección de archivos especificada por el usuario), o de que algunos de los " "gestores de contexto sean opcionales:" #: ../Doc/library/contextlib.rst:673 msgid "" "As shown, :class:`ExitStack` also makes it quite easy to use :keyword:`with` " "statements to manage arbitrary resources that don't natively support the " "context management protocol." msgstr "" "Como se muestra, :class:`ExitStack` también hace que sea bastante fácil de " "usar :keyword:`with` para administrar recursos arbitrarios que no admiten de " "forma nativa el protocolo de gestión de contexto." #: ../Doc/library/contextlib.rst:679 msgid "Catching exceptions from ``__enter__`` methods" msgstr "Capturando excepciones de los métodos ``__enter__``" #: ../Doc/library/contextlib.rst:681 msgid "" "It is occasionally desirable to catch exceptions from an ``__enter__`` " "method implementation, *without* inadvertently catching exceptions from the :" "keyword:`with` statement body or the context manager's ``__exit__`` method. " "By using :class:`ExitStack` the steps in the context management protocol can " "be separated slightly in order to allow this::" msgstr "" "Ocasionalmente es deseable capturar excepciones de una implementación del " "método ``__enter__``, *sin* capturar inadvertidamente excepciones del cuerpo " "de la declaración :keyword:`with` o el método ``__exit__`` del gestor de " "contexto. Al usar :class:`ExitStack`, los pasos en el protocolo de gestor de " "contexto se pueden separar ligeramente para permitir esto::" #: ../Doc/library/contextlib.rst:696 msgid "" "Actually needing to do this is likely to indicate that the underlying API " "should be providing a direct resource management interface for use with :" "keyword:`try`/:keyword:`except`/:keyword:`finally` statements, but not all " "APIs are well designed in that regard. When a context manager is the only " "resource management API provided, then :class:`ExitStack` can make it easier " "to handle various situations that can't be handled directly in a :keyword:" "`with` statement." msgstr "" "Es probable que la necesidad de hacer esto indique que la API subyacente " "debería proporcionar una interfaz de administración de recursos directa para " "usar con :keyword:`try`/:keyword:`except`/:keyword:`finally`, pero no todas " "las API están bien diseñados en ese sentido. Cuando un administrador de " "contexto es la única API de administración de recursos proporcionada, " "entonces :class:`ExitStack` puede facilitar el manejo de diversas " "situaciones que no se pueden manejar directamente en una declaración :" "keyword:`with`." #: ../Doc/library/contextlib.rst:706 msgid "Cleaning up in an ``__enter__`` implementation" msgstr "Limpieza en una implementación ``__enter__``" #: ../Doc/library/contextlib.rst:708 msgid "" "As noted in the documentation of :meth:`ExitStack.push`, this method can be " "useful in cleaning up an already allocated resource if later steps in the :" "meth:`__enter__` implementation fail." msgstr "" "Como se señala en la documentación de :meth:`ExitStack.push`, este método " "puede ser útil para limpiar un recurso ya asignado si fallan los pasos " "posteriores en :meth:`__enter__`." #: ../Doc/library/contextlib.rst:712 msgid "" "Here's an example of doing this for a context manager that accepts resource " "acquisition and release functions, along with an optional validation " "function, and maps them to the context management protocol::" msgstr "" "Aquí hay un ejemplo de cómo hacer esto para un administrador de contexto que " "acepta funciones de adquisición y liberación de recursos, junto con una " "función de validación opcional, y las asigna al protocolo de administración " "de contexto::" #: ../Doc/library/contextlib.rst:752 msgid "Replacing any use of ``try-finally`` and flag variables" msgstr "Reemplazar cualquier uso de ``try-finally`` y marcar variables" #: ../Doc/library/contextlib.rst:754 msgid "" "A pattern you will sometimes see is a ``try-finally`` statement with a flag " "variable to indicate whether or not the body of the ``finally`` clause " "should be executed. In its simplest form (that can't already be handled just " "by using an ``except`` clause instead), it looks something like this::" msgstr "" "Un patrón que a veces verá es una declaración de ``try-finally`` con una " "variable de indicador para indicar si el cuerpo de la cláusula ``finally`` " "debe ejecutarse o no. En su forma más simple (que ya no puede manejarse " "simplemente usando una cláusula ``except`` en su lugar), se parece a esto::" #: ../Doc/library/contextlib.rst:768 msgid "" "As with any ``try`` statement based code, this can cause problems for " "development and review, because the setup code and the cleanup code can end " "up being separated by arbitrarily long sections of code." msgstr "" "Al igual que con cualquier código basado en la declaración ``try``, esto " "puede causar problemas de desarrollo y revisión, porque el código de " "configuración y el código de limpieza pueden terminar separados por " "secciones de código arbitrariamente largas." #: ../Doc/library/contextlib.rst:772 msgid "" ":class:`ExitStack` makes it possible to instead register a callback for " "execution at the end of a ``with`` statement, and then later decide to skip " "executing that callback::" msgstr "" ":class:`ExitStack` hace posible registrar una retrollamada para su ejecución " "al final de una instrucción ``with``, y luego decide omitir la ejecución de " "esa retrollamada::" #: ../Doc/library/contextlib.rst:784 msgid "" "This allows the intended cleanup up behaviour to be made explicit up front, " "rather than requiring a separate flag variable." msgstr "" "Esto permite que el comportamiento de limpieza previsto se haga explícito " "por adelantado, en lugar de requerir una variable de indicador separada." #: ../Doc/library/contextlib.rst:787 msgid "" "If a particular application uses this pattern a lot, it can be simplified " "even further by means of a small helper class::" msgstr "" "Si una aplicación particular usa mucho este patrón, puede simplificarse aún " "más por medio de una pequeña clase auxiliar::" #: ../Doc/library/contextlib.rst:805 msgid "" "If the resource cleanup isn't already neatly bundled into a standalone " "function, then it is still possible to use the decorator form of :meth:" "`ExitStack.callback` to declare the resource cleanup in advance::" msgstr "" "Si la limpieza del recurso no está bien agrupada en una función " "independiente, entonces todavía es posible usar la forma decoradora de :meth:" "`ExitStack.callback` para declarar la limpieza del recurso por adelantado::" #: ../Doc/library/contextlib.rst:820 msgid "" "Due to the way the decorator protocol works, a callback function declared " "this way cannot take any parameters. Instead, any resources to be released " "must be accessed as closure variables." msgstr "" "Debido a la forma en que funciona el protocolo decorador, una función de " "retrollamada declarada de esta manera no puede tomar ningún parámetro. En " "cambio, se debe acceder a los recursos que se liberarán como variables de " "cierre." #: ../Doc/library/contextlib.rst:826 msgid "Using a context manager as a function decorator" msgstr "Usar un gestor de contexto como decorador de funciones" #: ../Doc/library/contextlib.rst:828 msgid "" ":class:`ContextDecorator` makes it possible to use a context manager in both " "an ordinary ``with`` statement and also as a function decorator." msgstr "" ":class:`ContextDecorator` hace posible usar un gestor de contexto tanto en " "una instrucción ordinaria ``with`` como también como decorador de funciones." #: ../Doc/library/contextlib.rst:831 msgid "" "For example, it is sometimes useful to wrap functions or groups of " "statements with a logger that can track the time of entry and time of exit. " "Rather than writing both a function decorator and a context manager for the " "task, inheriting from :class:`ContextDecorator` provides both capabilities " "in a single definition::" msgstr "" "Por ejemplo, a veces es útil envolver funciones o grupos de declaraciones " "con un registrador que puede rastrear la hora de entrada y la hora de " "salida. En lugar de escribir tanto un decorador de funciones como un " "administrador de contexto para la tarea, heredar de :class:" "`ContextDecorator` proporciona ambas capacidades en una sola definición::" #: ../Doc/library/contextlib.rst:852 msgid "Instances of this class can be used as both a context manager::" msgstr "" "Las instancias de esta clase se pueden usar como un gestor de contexto::" #: ../Doc/library/contextlib.rst:858 msgid "And also as a function decorator::" msgstr "Y también como decorador de funciones::" #: ../Doc/library/contextlib.rst:865 msgid "" "Note that there is one additional limitation when using context managers as " "function decorators: there's no way to access the return value of :meth:" "`__enter__`. If that value is needed, then it is still necessary to use an " "explicit ``with`` statement." msgstr "" "Tenga en cuenta que hay una limitación adicional cuando se usan " "administradores de contexto como decoradores de funciones: no hay forma de " "acceder al valor de retorno de :meth:`__enter__`. Si se necesita ese valor, " "aún es necesario usar una declaración explícita ``with``." #: ../Doc/library/contextlib.rst:873 msgid ":pep:`343` - The \"with\" statement" msgstr ":pep:`343` - La declaración \"with\"" #: ../Doc/library/contextlib.rst:873 msgid "" "The specification, background, and examples for the Python :keyword:`with` " "statement." msgstr "" "La especificación, antecedentes y ejemplos de la declaración de Python :" "keyword:`with`." #: ../Doc/library/contextlib.rst:879 msgid "Single use, reusable and reentrant context managers" msgstr "Gestores de contexto de uso único, reutilizables y reentrantes" #: ../Doc/library/contextlib.rst:881 msgid "" "Most context managers are written in a way that means they can only be used " "effectively in a :keyword:`with` statement once. These single use context " "managers must be created afresh each time they're used - attempting to use " "them a second time will trigger an exception or otherwise not work correctly." msgstr "" "La mayoría de los gestores de contexto están escritos de una manera que " "significa que solo se pueden usar de manera efectiva en una declaración :" "keyword:`with` una vez. Estos administradores de contexto de un solo uso " "deben crearse de nuevo cada vez que se usan; si intenta usarlos por segunda " "vez, se activará una excepción o, de lo contrario, no funcionará " "correctamente." #: ../Doc/library/contextlib.rst:887 msgid "" "This common limitation means that it is generally advisable to create " "context managers directly in the header of the :keyword:`with` statement " "where they are used (as shown in all of the usage examples above)." msgstr "" "Esta limitación común significa que generalmente es aconsejable crear " "gestores de contexto directamente en el encabezado de la palabra clave :" "keyword:`with` donde se usan (como se muestra en todos los ejemplos de uso " "anteriores)." #: ../Doc/library/contextlib.rst:891 msgid "" "Files are an example of effectively single use context managers, since the " "first :keyword:`with` statement will close the file, preventing any further " "IO operations using that file object." msgstr "" "Los archivos son un ejemplo de gestores de contexto de un solo uso, ya que " "la primera :keyword:`with` cerrará el archivo, evitando cualquier otra " "operación de E/S que use ese objeto de archivo." #: ../Doc/library/contextlib.rst:895 msgid "" "Context managers created using :func:`contextmanager` are also single use " "context managers, and will complain about the underlying generator failing " "to yield if an attempt is made to use them a second time::" msgstr "" "Los gestores de contexto creados usando :func:`contextmanager` también son " "gestores de contexto de un solo uso, y se quejarán de la falla del generador " "subyacente si se intenta usarlos por segunda vez::" #: ../Doc/library/contextlib.rst:923 msgid "Reentrant context managers" msgstr "Gestores contextuales reentrantes" #: ../Doc/library/contextlib.rst:925 msgid "" "More sophisticated context managers may be \"reentrant\". These context " "managers can not only be used in multiple :keyword:`with` statements, but " "may also be used *inside* a :keyword:`!with` statement that is already using " "the same context manager." msgstr "" "Los gestores de contexto más sofisticados pueden ser \"reentrantes\". Estos " "administradores de contexto no solo se pueden usar en múltiples " "declaraciones :keyword:`with`, sino que también se pueden usar *inside* a :" "keyword:`!with` que ya está usando el mismo gestor de contexto." #: ../Doc/library/contextlib.rst:930 #, fuzzy msgid "" ":class:`threading.RLock` is an example of a reentrant context manager, as " "are :func:`suppress`, :func:`redirect_stdout`, and :func:`chdir`. Here's a " "very simple example of reentrant use::" msgstr "" ":class:`threading.RLock` es un ejemplo de un administrador de contexto " "reentrante, como son :func:`suppress` y :func:`redirect_stdout`. Aquí hay un " "ejemplo muy simple de uso reentrante::" #: ../Doc/library/contextlib.rst:949 msgid "" "Real world examples of reentrancy are more likely to involve multiple " "functions calling each other and hence be far more complicated than this " "example." msgstr "" "Es más probable que los ejemplos del mundo real de reentrada impliquen " "múltiples funciones que se llaman entre sí y, por lo tanto, sean mucho más " "complicadas que este ejemplo." #: ../Doc/library/contextlib.rst:953 msgid "" "Note also that being reentrant is *not* the same thing as being thread " "safe. :func:`redirect_stdout`, for example, is definitely not thread safe, " "as it makes a global modification to the system state by binding :data:`sys." "stdout` to a different stream." msgstr "" "Tenga en cuenta también que ser reentrante *no* es lo mismo que ser seguro " "para subprocesos. :func:`redirect_stdout`, por ejemplo, definitivamente no " "es seguro para subprocesos, ya que realiza una modificación global al estado " "del sistema al vincular :data:`sys.stdout` a una secuencia diferente." #: ../Doc/library/contextlib.rst:962 msgid "Reusable context managers" msgstr "Gestores contextuales reutilizables" #: ../Doc/library/contextlib.rst:964 msgid "" "Distinct from both single use and reentrant context managers are " "\"reusable\" context managers (or, to be completely explicit, \"reusable, " "but not reentrant\" context managers, since reentrant context managers are " "also reusable). These context managers support being used multiple times, " "but will fail (or otherwise not work correctly) if the specific context " "manager instance has already been used in a containing with statement." msgstr "" "Distintos de los administradores de contexto de uso único y reentrante son " "los administradores de contexto \"reutilizables\" (o, para ser completamente " "explícitos, los administradores de contexto \"reutilizables, pero no " "reentrantes\", ya que los administradores de contexto reentrantes también " "son reutilizables). Estos administradores de contexto admiten que se usen " "varias veces, pero fallarán (o de lo contrario no funcionarán correctamente) " "si la instancia específica del administrador de contexto ya se ha utilizado " "en una declaración que contiene." #: ../Doc/library/contextlib.rst:971 msgid "" ":class:`threading.Lock` is an example of a reusable, but not reentrant, " "context manager (for a reentrant lock, it is necessary to use :class:" "`threading.RLock` instead)." msgstr "" ":class:`threading.Lock` es un ejemplo de un gestor de contexto reutilizable, " "pero no reentrante (para un bloqueo reentrante, es necesario usar :class:" "`threading.RLock` en su lugar)." #: ../Doc/library/contextlib.rst:975 msgid "" "Another example of a reusable, but not reentrant, context manager is :class:" "`ExitStack`, as it invokes *all* currently registered callbacks when leaving " "any with statement, regardless of where those callbacks were added::" msgstr "" "Otro ejemplo de un administrador de contexto reutilizable, pero no " "reentrante es :class:`ExitStack`, ya que invoca *all* las retrollamadas " "registradas actualmente al dejar cualquier con declaración, " "independientemente de dónde se agregaron esas retrollamadas::" #: ../Doc/library/contextlib.rst:1006 msgid "" "As the output from the example shows, reusing a single stack object across " "multiple with statements works correctly, but attempting to nest them will " "cause the stack to be cleared at the end of the innermost with statement, " "which is unlikely to be desirable behaviour." msgstr "" "Como muestra el resultado del ejemplo, la reutilización de un solo objeto de " "pila en múltiples con declaraciones funciona correctamente, pero intentar " "anidarlos hará que la pila se borre al final de la declaración más interna, " "lo que es poco probable que sea un comportamiento deseable." #: ../Doc/library/contextlib.rst:1011 msgid "" "Using separate :class:`ExitStack` instances instead of reusing a single " "instance avoids that problem::" msgstr "" "El uso de instancias separadas :class:`ExitStack` en lugar de reutilizar una " "sola instancia evita ese problema::"