# 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: 2023-10-12 19:43+0200\n" "PO-Revision-Date: 2023-10-23 10:45-0300\n" "Last-Translator: Carlos A. Crespo \n" "Language-Team: python-doc-es\n" "Language: es\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "Generated-By: Babel 2.13.0\n" "X-Generator: Poedit 3.0.1\n" #: ../Doc/tutorial/modules.rst:5 msgid "Modules" msgstr "Módulos" #: ../Doc/tutorial/modules.rst:7 msgid "" "If you quit from the Python interpreter and enter it again, the definitions " "you have made (functions and variables) are lost. Therefore, if you want to " "write a somewhat longer program, you are better off using a text editor to " "prepare the input for the interpreter and running it with that file as input " "instead. This is known as creating a *script*. As your program gets " "longer, you may want to split it into several files for easier maintenance. " "You may also want to use a handy function that you've written in several " "programs without copying its definition into each program." msgstr "" "Si sales del intérprete de Python y vuelves a entrar, las definiciones que " "habías hecho (funciones y variables) se pierden. Por lo tanto, si quieres " "escribir un programa más o menos largo, es mejor que utilices un editor de " "texto para preparar la entrada para el intérprete y ejecutarlo con ese " "archivo como entrada. Esto se conoce como crear un *script*. A medida que tu " "programa crezca, quizás quieras separarlo en varios archivos para que el " "mantenimiento sea más sencillo. Quizás también quieras usar una función útil " "que has escrito en distintos programas sin copiar su definición en cada " "programa." #: ../Doc/tutorial/modules.rst:16 msgid "" "To support this, Python has a way to put definitions in a file and use them " "in a script or in an interactive instance of the interpreter. Such a file is " "called a *module*; definitions from a module can be *imported* into other " "modules or into the *main* module (the collection of variables that you have " "access to in a script executed at the top level and in calculator mode)." msgstr "" "Para soportar esto, Python tiene una manera de poner definiciones en un " "archivo y usarlos en un script o en una instancia del intérprete. Este tipo " "de ficheros se llama *módulo*; las definiciones de un módulo pueden ser " "*importadas* a otros módulos o al módulo *principal* (la colección de " "variables a las que tienes acceso en un script ejecutado en el nivel " "superior y en el modo calculadora)." #: ../Doc/tutorial/modules.rst:22 msgid "" "A module is a file containing Python definitions and statements. The file " "name is the module name with the suffix :file:`.py` appended. Within a " "module, the module's name (as a string) is available as the value of the " "global variable ``__name__``. For instance, use your favorite text editor " "to create a file called :file:`fibo.py` in the current directory with the " "following contents::" msgstr "" "Un módulo es un fichero conteniendo definiciones y declaraciones de Python. " "El nombre de archivo es el nombre del módulo con el sufijo :file:`.py` " "agregado. Dentro de un módulo, el nombre del mismo módulo (como cadena) está " "disponible en el valor de la variable global ``__name__``. Por ejemplo, " "utiliza tu editor de texto favorito para crear un archivo llamado :file:" "`fibo.py` en el directorio actual, con el siguiente contenido::" #: ../Doc/tutorial/modules.rst:45 msgid "" "Now enter the Python interpreter and import this module with the following " "command::" msgstr "" "Ahora entra en el intérprete de Python e importa este modulo con el " "siguiente comando::" #: ../Doc/tutorial/modules.rst:50 msgid "" "This does not add the names of the functions defined in ``fibo`` directly " "to the current :term:`namespace` (see :ref:`tut-scopes` for more details); " "it only adds the module name ``fibo`` there. Using the module name you can " "access the functions::" msgstr "" "Esto no añade los nombres de las funciones definidas en ``fibo`` " "directamente al actual :term:`namespace` (ver :ref:`tut-scopes` para más " "detalles); sólo añade el nombre del módulo ``fibo`` allí. Usando el nombre " "del módulo puedes acceder a las funciones::" #: ../Doc/tutorial/modules.rst:62 msgid "" "If you intend to use a function often you can assign it to a local name::" msgstr "" "Si pretendes utilizar una función frecuentemente puedes asignarla a un " "nombre local::" #: ../Doc/tutorial/modules.rst:72 msgid "More on Modules" msgstr "Más sobre los módulos" #: ../Doc/tutorial/modules.rst:74 msgid "" "A module can contain executable statements as well as function definitions. " "These statements are intended to initialize the module. They are executed " "only the *first* time the module name is encountered in an import statement. " "[#]_ (They are also run if the file is executed as a script.)" msgstr "" "Un módulo puede contener tanto declaraciones ejecutables como definiciones " "de funciones. Estas declaraciones están pensadas para inicializar el módulo. " "Se ejecutan únicamente la *primera* vez que el módulo se encuentra en una " "declaración import. [#]_ (También se ejecutan si el archivo se ejecuta como " "script.)" #: ../Doc/tutorial/modules.rst:79 msgid "" "Each module has its own private namespace, which is used as the global " "namespace by all functions defined in the module. Thus, the author of a " "module can use global variables in the module without worrying about " "accidental clashes with a user's global variables. On the other hand, if you " "know what you are doing you can touch a module's global variables with the " "same notation used to refer to its functions, ``modname.itemname``." msgstr "" "Cada módulo tiene su propio espacio de nombres privado, que es utilizado " "como espacio de nombres global por todas las funciones definidas en el " "módulo. De este modo, el autor de un módulo puede utilizar variables " "globales en el módulo sin preocuparse por choques accidentales con las " "variables globales de un usuario. Por otro lado, si sabes lo que estás " "haciendo puedes tocar las variables globales de un módulo con la misma " "notación que se utiliza para referirse a sus funciones, ``modname.itemname``." #: ../Doc/tutorial/modules.rst:86 msgid "" "Modules can import other modules. It is customary but not required to place " "all :keyword:`import` statements at the beginning of a module (or script, " "for that matter). The imported module names, if placed at the top level of " "a module (outside any functions or classes), are added to the module's " "global namespace." msgstr "" "Los módulos pueden importar otros módulos. Es costumbre pero no obligatorio " "ubicar todas las declaraciones :keyword:`import` al principio del módulo (o " "script, para el caso). Los nombres de los módulos importados, si se colocan " "en el nivel superior de un módulo (fuera de cualquier función o clase), se " "añaden al espacio de nombres global del módulo." #: ../Doc/tutorial/modules.rst:91 msgid "" "There is a variant of the :keyword:`import` statement that imports names " "from a module directly into the importing module's namespace. For example::" msgstr "" "Hay una variante de la declaración :keyword:`import` que importa los nombres " "de un módulo directamente al espacio de nombres del módulo que hace la " "importación. Por ejemplo::" #: ../Doc/tutorial/modules.rst:98 msgid "" "This does not introduce the module name from which the imports are taken in " "the local namespace (so in the example, ``fibo`` is not defined)." msgstr "" "Esto no introduce en el espacio de nombres local el nombre del módulo desde " "el cual se está importando (por lo tanto, en el ejemplo, ``fibo`` no esta " "definido)." #: ../Doc/tutorial/modules.rst:101 msgid "There is even a variant to import all names that a module defines::" msgstr "" "Hay incluso una variante para importar todos los nombres que un módulo " "define::" #: ../Doc/tutorial/modules.rst:107 msgid "" "This imports all names except those beginning with an underscore (``_``). In " "most cases Python programmers do not use this facility since it introduces " "an unknown set of names into the interpreter, possibly hiding some things " "you have already defined." msgstr "" "Esto importa todos los nombres excepto los que inician con un guión bajo " "(``_``). La mayoría de las veces los programadores de Python no usan esto ya " "que introduce en el intérprete un conjunto de nombres desconocido, " "posiblemente escondiendo algunas de las definiciones previas." #: ../Doc/tutorial/modules.rst:112 msgid "" "Note that in general the practice of importing ``*`` from a module or " "package is frowned upon, since it often causes poorly readable code. " "However, it is okay to use it to save typing in interactive sessions." msgstr "" "Nótese que en general la práctica de importar ``*`` de un módulo o paquete " "está muy mal vista, ya que frecuentemente genera código poco legible. Sin " "embargo, está bien usarlo para ahorrar tecleo en sesiones interactivas." #: ../Doc/tutorial/modules.rst:116 msgid "" "If the module name is followed by :keyword:`!as`, then the name following :" "keyword:`!as` is bound directly to the imported module." msgstr "" "Si el nombre del módulo es seguido por :keyword:`!as`, el nombre siguiendo :" "keyword:`!as` queda ligado directamente al módulo importado." #: ../Doc/tutorial/modules.rst:125 msgid "" "This is effectively importing the module in the same way that ``import " "fibo`` will do, with the only difference of it being available as ``fib``." msgstr "" "Esto es básicamente importar el módulo de la misma forma que se haría con " "``import fibo``, con la única diferencia en que se encuentra accesible como " "``fib``." #: ../Doc/tutorial/modules.rst:128 msgid "" "It can also be used when utilising :keyword:`from` with similar effects::" msgstr "" "También se puede utilizar cuando se utiliza :keyword:`from` con efectos " "similares::" #: ../Doc/tutorial/modules.rst:137 msgid "" "For efficiency reasons, each module is only imported once per interpreter " "session. Therefore, if you change your modules, you must restart the " "interpreter -- or, if it's just one module you want to test interactively, " "use :func:`importlib.reload`, e.g. ``import importlib; importlib." "reload(modulename)``." msgstr "" "Por razones de eficiencia, cada módulo es importado solo una vez por sesión " "del intérprete. Por lo tanto, si cambias tus módulos, debes reiniciar el " "interprete -- ó, si es un solo módulo que quieres probar de forma " "interactiva, usa :func:`importlib.reload`, por ejemplo: ``import importlib; " "importlib.reload(modulename)``." #: ../Doc/tutorial/modules.rst:147 msgid "Executing modules as scripts" msgstr "Ejecutar módulos como scripts" #: ../Doc/tutorial/modules.rst:149 msgid "When you run a Python module with ::" msgstr "Cuando ejecutes un módulo de Python con ::" #: ../Doc/tutorial/modules.rst:153 msgid "" "the code in the module will be executed, just as if you imported it, but " "with the ``__name__`` set to ``\"__main__\"``. That means that by adding " "this code at the end of your module::" msgstr "" "el código en el módulo será ejecutado, tal como si lo hubieses importado, " "pero con ``__name__`` con el valor de ``\"__main__\"``. Eso significa que " "agregando este código al final de tu módulo::" #: ../Doc/tutorial/modules.rst:161 msgid "" "you can make the file usable as a script as well as an importable module, " "because the code that parses the command line only runs if the module is " "executed as the \"main\" file:" msgstr "" "puedes hacer que el archivo sea utilizable tanto como script, como módulo " "importable, porque el código que analiza la línea de órdenes sólo se ejecuta " "si el módulo es ejecutado como archivo principal:" #: ../Doc/tutorial/modules.rst:170 msgid "If the module is imported, the code is not run::" msgstr "Si el módulo se importa, ese código no se ejecuta::" #: ../Doc/tutorial/modules.rst:175 msgid "" "This is often used either to provide a convenient user interface to a " "module, or for testing purposes (running the module as a script executes a " "test suite)." msgstr "" "Esto es frecuentemente usado para proveer al módulo una interfaz de usuario " "conveniente, o para fines de prueba (ejecutar el módulo como un script que " "ejecuta un conjunto de pruebas)." #: ../Doc/tutorial/modules.rst:182 msgid "The Module Search Path" msgstr "El camino de búsqueda de los módulos" #: ../Doc/tutorial/modules.rst:186 msgid "" "When a module named :mod:`!spam` is imported, the interpreter first searches " "for a built-in module with that name. These module names are listed in :data:" "`sys.builtin_module_names`. If not found, it then searches for a file named :" "file:`spam.py` in a list of directories given by the variable :data:`sys." "path`. :data:`sys.path` is initialized from these locations:" msgstr "" "Cuando se importa un módulo llamado :mod:`!spam`, el intérprete busca " "primero por un módulo con ese nombre que esté integrado en el intérprete. " "Estos nombres de módulos están listados en :data:`sys.builtin_module_names`. " "Si no lo encuentra, entonces busca un archivo llamado :file:`spam.py` en una " "lista de directorios especificada por la variable :data:`sys.path`. :data:" "`sys.path` se inicializa con las siguientes ubicaciones:" #: ../Doc/tutorial/modules.rst:192 msgid "" "The directory containing the input script (or the current directory when no " "file is specified)." msgstr "" "El directorio que contiene el script de entrada (o el directorio actual " "cuando no se especifica archivo)." #: ../Doc/tutorial/modules.rst:194 msgid "" ":envvar:`PYTHONPATH` (a list of directory names, with the same syntax as the " "shell variable :envvar:`PATH`)." msgstr "" ":envvar:`PYTHONPATH` (una lista de nombres de directorios, con la misma " "sintaxis que la variable de la terminal :envvar:`PATH`)." #: ../Doc/tutorial/modules.rst:196 msgid "" "The installation-dependent default (by convention including a ``site-" "packages`` directory, handled by the :mod:`site` module)." msgstr "" "El valor predeterminado dependiente de la instalación (por convención " "incluye un directorio ``site-packages``, manejado por el módulo :mod:`site`)." #: ../Doc/tutorial/modules.rst:199 msgid "More details are at :ref:`sys-path-init`." msgstr "Más detalles en :ref:`sys-path-init`." #: ../Doc/tutorial/modules.rst:202 msgid "" "On file systems which support symlinks, the directory containing the input " "script is calculated after the symlink is followed. In other words the " "directory containing the symlink is **not** added to the module search path." msgstr "" "En los sistemas de archivo que soportan enlaces simbólicos, el directorio " "que contiene el script de entrada es calculado luego de seguir el enlace " "simbólico. En otras palabras, el directorio que contiene el enlace simbólico " "**no** es agregado al camino de búsqueda del módulo." #: ../Doc/tutorial/modules.rst:206 msgid "" "After initialization, Python programs can modify :data:`sys.path`. The " "directory containing the script being run is placed at the beginning of the " "search path, ahead of the standard library path. This means that scripts in " "that directory will be loaded instead of modules of the same name in the " "library directory. This is an error unless the replacement is intended. See " "section :ref:`tut-standardmodules` for more information." msgstr "" "Luego de la inicialización, los programas Python pueden modificar :data:`sys." "path`. El directorio que contiene el script que se está ejecutando se ubica " "al principio de la búsqueda, adelante de la biblioteca estándar. Esto " "significa que se cargarán scripts en ese directorio en lugar de módulos de " "la biblioteca estándar con el mismo nombre. Esto es un error a menos que se " "esté reemplazando intencionalmente. Mirá la sección :ref:`tut-" "standardmodules` para más información." #: ../Doc/tutorial/modules.rst:219 msgid "\"Compiled\" Python files" msgstr "Archivos \"compilados\" de Python" #: ../Doc/tutorial/modules.rst:221 msgid "" "To speed up loading modules, Python caches the compiled version of each " "module in the ``__pycache__`` directory under the name :file:`module." "{version}.pyc`, where the version encodes the format of the compiled file; " "it generally contains the Python version number. For example, in CPython " "release 3.3 the compiled version of spam.py would be cached as ``__pycache__/" "spam.cpython-33.pyc``. This naming convention allows compiled modules from " "different releases and different versions of Python to coexist." msgstr "" "Para acelerar la carga de módulos, Python cachea las versiones compiladas de " "cada módulo en el directorio ``__pycache__`` bajo el nombre :file:`module." "{version}.pyc`, dónde la versión codifica el formato del archivo compilado; " "generalmente contiene el número de versión de Python. Por ejemplo, en " "CPython *release* 3.3 la versión compilada de spam.py sería cacheada como " "``__pycache__/spam.cpython-33.pyc``. Este convención de nombre permite " "compilar módulos desde diferentes *releases* y versiones de Python para " "coexistir." #: ../Doc/tutorial/modules.rst:229 msgid "" "Python checks the modification date of the source against the compiled " "version to see if it's out of date and needs to be recompiled. This is a " "completely automatic process. Also, the compiled modules are platform-" "independent, so the same library can be shared among systems with different " "architectures." msgstr "" "Python chequea la fecha de modificación de la fuente contra la versión " "compilada para ver si esta es obsoleta y necesita ser recompilada. Esto es " "un proceso completamente automático. También, los módulos compilados son " "independientes de la plataforma, así que la misma biblioteca puede ser " "compartida a través de sistemas con diferentes arquitecturas." #: ../Doc/tutorial/modules.rst:234 msgid "" "Python does not check the cache in two circumstances. First, it always " "recompiles and does not store the result for the module that's loaded " "directly from the command line. Second, it does not check the cache if " "there is no source module. To support a non-source (compiled only) " "distribution, the compiled module must be in the source directory, and there " "must not be a source module." msgstr "" "Python no chequea el caché en dos circunstancias. Primero, siempre recompila " "y no graba el resultado del módulo que es cargado directamente desde la " "línea de comando. Segundo, no chequea el caché si no hay módulo fuente. Para " "soportar una distribución sin fuente (solo compilada), el módulo compilado " "debe estar en el directorio origen, y no debe haber un módulo fuente." #: ../Doc/tutorial/modules.rst:241 msgid "Some tips for experts:" msgstr "Algunos consejos para expertos:" #: ../Doc/tutorial/modules.rst:243 msgid "" "You can use the :option:`-O` or :option:`-OO` switches on the Python command " "to reduce the size of a compiled module. The ``-O`` switch removes assert " "statements, the ``-OO`` switch removes both assert statements and __doc__ " "strings. Since some programs may rely on having these available, you should " "only use this option if you know what you're doing. \"Optimized\" modules " "have an ``opt-`` tag and are usually smaller. Future releases may change " "the effects of optimization." msgstr "" "Puedes usar los modificadores :option:`-O` o :option:`-OO` en el comando de " "Python para reducir el tamaño del módulo compilado. El modificador ``-O`` " "remueve las declaraciones *assert*, el modificador ``-OO`` remueve " "declaraciones *assert* y cadenas *__doc__*. Dado que algunos programas " "pueden confiar en tenerlos disponibles, solo deberías usar esta opción si " "conoces lo que estás haciendo. Los módulos \"optimizados\" tienen una " "etiqueta ``opt-`` y generalmente son mas pequeños. *Releases* futuras pueden " "cambiar los efectos de la optimización." #: ../Doc/tutorial/modules.rst:251 msgid "" "A program doesn't run any faster when it is read from a ``.pyc`` file than " "when it is read from a ``.py`` file; the only thing that's faster about ``." "pyc`` files is the speed with which they are loaded." msgstr "" "Un programa no se ejecuta mas rápido cuando es leído de un archivo ``.pyc`` " "que cuando es leído de un archivo ``.py``; la única cosa que es mas rápida " "en los archivos ``.pyc`` es la velocidad con la cual son cargados." #: ../Doc/tutorial/modules.rst:255 msgid "" "The module :mod:`compileall` can create .pyc files for all modules in a " "directory." msgstr "" "El módulo :mod:`compileall` puede crear archivos .pyc para todos los módulos " "en un directorio." #: ../Doc/tutorial/modules.rst:258 msgid "" "There is more detail on this process, including a flow chart of the " "decisions, in :pep:`3147`." msgstr "" "Hay mas detalle de este proceso, incluyendo un diagrama de flujo de " "decisiones, en :pep:`3147`." #: ../Doc/tutorial/modules.rst:265 msgid "Standard Modules" msgstr "Módulos estándar" #: ../Doc/tutorial/modules.rst:269 msgid "" "Python comes with a library of standard modules, described in a separate " "document, the Python Library Reference (\"Library Reference\" hereafter). " "Some modules are built into the interpreter; these provide access to " "operations that are not part of the core of the language but are " "nevertheless built in, either for efficiency or to provide access to " "operating system primitives such as system calls. The set of such modules " "is a configuration option which also depends on the underlying platform. " "For example, the :mod:`winreg` module is only provided on Windows systems. " "One particular module deserves some attention: :mod:`sys`, which is built " "into every Python interpreter. The variables ``sys.ps1`` and ``sys.ps2`` " "define the strings used as primary and secondary prompts::" msgstr "" "Python viene con una biblioteca de módulos estándar, descrita en un " "documento separado, la Referencia de la Biblioteca de Python (de aquí en " "más, \"Referencia de la Biblioteca\"). Algunos módulos se integran en el " "intérprete; estos proveen acceso a operaciones que no son parte del núcleo " "del lenguaje pero que sin embargo están integrados, tanto por eficiencia " "como para proveer acceso a primitivas del sistema operativo, como llamadas " "al sistema. El conjunto de tales módulos es una opción de configuración que " "también depende de la plataforma subyacente. Por ejemplo, el módulo :mod:" "`winreg` sólo se provee en sistemas Windows. Un módulo en particular merece " "algo de atención: :mod:`sys`, el que está integrado en todos los intérpretes " "de Python. Las variables ``sys.ps1`` y ``sys.ps2`` definen las cadenas " "usadas como cursores primarios y secundarios::" #: ../Doc/tutorial/modules.rst:292 msgid "" "These two variables are only defined if the interpreter is in interactive " "mode." msgstr "" "Estas dos variables están solamente definidas si el intérprete está en modo " "interactivo." #: ../Doc/tutorial/modules.rst:294 msgid "" "The variable ``sys.path`` is a list of strings that determines the " "interpreter's search path for modules. It is initialized to a default path " "taken from the environment variable :envvar:`PYTHONPATH`, or from a built-in " "default if :envvar:`PYTHONPATH` is not set. You can modify it using " "standard list operations::" msgstr "" "La variable ``sys.path`` es una lista de cadenas que determinan el camino de " "búsqueda del intérprete para los módulos. Se inicializa por omisión a un " "camino tomado de la variable de entorno :envvar:`PYTHONPATH`, o a un valor " "predefinido en el intérprete si :envvar:`PYTHONPATH` no está configurada. Lo " "puedes modificar usando las operaciones estándar de listas::" #: ../Doc/tutorial/modules.rst:307 msgid "The :func:`dir` Function" msgstr "La función :func:`dir`" #: ../Doc/tutorial/modules.rst:309 msgid "" "The built-in function :func:`dir` is used to find out which names a module " "defines. It returns a sorted list of strings::" msgstr "" "La función integrada :func:`dir` se usa para encontrar qué nombres define un " "módulo. Retorna una lista ordenada de cadenas::" #: ../Doc/tutorial/modules.rst:338 msgid "" "Without arguments, :func:`dir` lists the names you have defined currently::" msgstr "" "Sin argumentos, :func:`dir` lista los nombres que tienes actualmente " "definidos::" #: ../Doc/tutorial/modules.rst:346 msgid "" "Note that it lists all types of names: variables, modules, functions, etc." msgstr "" "Nótese que lista todos los tipos de nombres: variables, módulos, funciones, " "etc." #: ../Doc/tutorial/modules.rst:350 msgid "" ":func:`dir` does not list the names of built-in functions and variables. If " "you want a list of those, they are defined in the standard module :mod:" "`builtins`::" msgstr "" ":func:`dir` no lista los nombres de las funciones y variables integradas. Si " "quieres una lista de esos, están definidos en el módulo estándar :mod:" "`builtins`::" #: ../Doc/tutorial/modules.rst:389 msgid "Packages" msgstr "Paquetes" #: ../Doc/tutorial/modules.rst:391 msgid "" "Packages are a way of structuring Python's module namespace by using " "\"dotted module names\". For example, the module name :mod:`!A.B` " "designates a submodule named ``B`` in a package named ``A``. Just like the " "use of modules saves the authors of different modules from having to worry " "about each other's global variable names, the use of dotted module names " "saves the authors of multi-module packages like NumPy or Pillow from having " "to worry about each other's module names." msgstr "" "Los Paquetes son una forma de estructurar el espacio de nombres de módulos " "de Python usando \"nombres de módulo con puntos\". Por ejemplo, el nombre " "del módulo :mod:`!A.B` designa un submódulo ``B`` en un paquete llamado " "``A``. Así como el uso de módulos salva a los autores de diferentes módulos " "de tener que preocuparse por los nombres de las variables globales de los " "demás, el uso de nombres de módulo con puntos evita que los autores de " "paquetes multimódulos, como NumPy o Pillow, tengan que preocuparse por los " "nombres de los módulos de los demás." #: ../Doc/tutorial/modules.rst:399 msgid "" "Suppose you want to design a collection of modules (a \"package\") for the " "uniform handling of sound files and sound data. There are many different " "sound file formats (usually recognized by their extension, for example: :" "file:`.wav`, :file:`.aiff`, :file:`.au`), so you may need to create and " "maintain a growing collection of modules for the conversion between the " "various file formats. There are also many different operations you might " "want to perform on sound data (such as mixing, adding echo, applying an " "equalizer function, creating an artificial stereo effect), so in addition " "you will be writing a never-ending stream of modules to perform these " "operations. Here's a possible structure for your package (expressed in " "terms of a hierarchical filesystem):" msgstr "" "Supongamos que quieres designar una colección de módulos (un \"paquete\") " "para el manejo uniforme de archivos y datos de sonidos. Hay diferentes " "formatos de archivos de sonido (normalmente reconocidos por su extensión, " "por ejemplo: :file:`.wav`, :file:`.aiff`, :file:`.au`), por lo que tienes " "que crear y mantener una colección siempre creciente de módulos para la " "conversión entre los distintos formatos de archivos. Hay muchas operaciones " "diferentes que quizás quieras ejecutar en los datos de sonido (como " "mezclarlos, añadir eco, aplicar una función ecualizadora, crear un efecto " "estéreo artificial), por lo que además estarás escribiendo una lista sin fin " "de módulos para realizar estas operaciones. Aquí hay una posible estructura " "para tu paquete (expresados en términos de un sistema jerárquico de " "archivos):" #: ../Doc/tutorial/modules.rst:436 msgid "" "When importing the package, Python searches through the directories on ``sys." "path`` looking for the package subdirectory." msgstr "" "Al importar el paquete, Python busca a través de los directorios en ``sys." "path``, buscando el sub-directorio del paquete." #: ../Doc/tutorial/modules.rst:439 msgid "" "The :file:`__init__.py` files are required to make Python treat directories " "containing the file as packages. This prevents directories with a common " "name, such as ``string``, from unintentionally hiding valid modules that " "occur later on the module search path. In the simplest case, :file:`__init__." "py` can just be an empty file, but it can also execute initialization code " "for the package or set the ``__all__`` variable, described later." msgstr "" "Los archivos :file:`__init__.py` son obligatorios para que Python trate los " "directorios que contienen los archivos como paquetes. Esto evita que los " "directorios con un nombre común, como ``string``, oculten involuntariamente " "módulos válidos que se producen luego en el camino de búsqueda del módulo. " "En el caso mas simple, :file:`__init__.py` puede ser solo un archivo vacío, " "pero también puede ejecutar código de inicialización para el paquete o el " "conjunto de variables ``__all__``, descriptas luego." #: ../Doc/tutorial/modules.rst:446 msgid "" "Users of the package can import individual modules from the package, for " "example::" msgstr "" "Los usuarios del paquete pueden importar módulos individuales del mismo, por " "ejemplo::" #: ../Doc/tutorial/modules.rst:451 msgid "" "This loads the submodule :mod:`!sound.effects.echo`. It must be referenced " "with its full name. ::" msgstr "" "Esto carga el submódulo :mod:`!sound.effects.echo`. Debe hacerse referencia " "al mismo con el nombre completo. ::" #: ../Doc/tutorial/modules.rst:456 msgid "An alternative way of importing the submodule is::" msgstr "Otra alternativa para importar el submódulo es::" #: ../Doc/tutorial/modules.rst:460 msgid "" "This also loads the submodule :mod:`!echo`, and makes it available without " "its package prefix, so it can be used as follows::" msgstr "" "Esto también carga el submódulo :mod:`!echo`, y lo deja disponible sin su " "prefijo de paquete, por lo que puede usarse así::" #: ../Doc/tutorial/modules.rst:465 msgid "" "Yet another variation is to import the desired function or variable " "directly::" msgstr "" "Otra variación más es importar la función o variable deseadas directamente::" #: ../Doc/tutorial/modules.rst:469 msgid "" "Again, this loads the submodule :mod:`!echo`, but this makes its function :" "func:`!echofilter` directly available::" msgstr "" "De nuevo, esto carga el submódulo :mod:`!echo`, pero deja directamente " "disponible a la función :func:`!echofilter`::" #: ../Doc/tutorial/modules.rst:474 msgid "" "Note that when using ``from package import item``, the item can be either a " "submodule (or subpackage) of the package, or some other name defined in the " "package, like a function, class or variable. The ``import`` statement first " "tests whether the item is defined in the package; if not, it assumes it is a " "module and attempts to load it. If it fails to find it, an :exc:" "`ImportError` exception is raised." msgstr "" "Nótese que al usar ``from package import item``, el ítem puede ser tanto un " "submódulo (o subpaquete) del paquete, o algún otro nombre definido en el " "paquete, como una función, clase, o variable. La declaración ``import`` " "primero verifica si el ítem está definido en el paquete; si no, asume que es " "un módulo y trata de cargarlo. Si no lo puede encontrar, se genera una " "excepción :exc:`ImportError`." #: ../Doc/tutorial/modules.rst:481 msgid "" "Contrarily, when using syntax like ``import item.subitem.subsubitem``, each " "item except for the last must be a package; the last item can be a module or " "a package but can't be a class or function or variable defined in the " "previous item." msgstr "" "Por otro lado, cuando se usa la sintaxis como ``import item.subitem." "subsubitem``, cada ítem excepto el último debe ser un paquete; el mismo " "puede ser un módulo o un paquete pero no puede ser una clase, función o " "variable definida en el ítem previo." #: ../Doc/tutorial/modules.rst:490 msgid "Importing \\* From a Package" msgstr "Importar \\* desde un paquete" #: ../Doc/tutorial/modules.rst:494 msgid "" "Now what happens when the user writes ``from sound.effects import *``? " "Ideally, one would hope that this somehow goes out to the filesystem, finds " "which submodules are present in the package, and imports them all. This " "could take a long time and importing sub-modules might have unwanted side-" "effects that should only happen when the sub-module is explicitly imported." msgstr "" "Ahora, ¿qué sucede cuando el usuario escribe ``from sound.effects import " "*``? Idealmente, uno esperaría que esto de alguna manera vaya al sistema de " "archivos, encuentre cuales submódulos están presentes en el paquete, y los " "importe a todos. Esto puede tardar mucho y el importar sub-módulos puede " "tener efectos secundarios no deseados que sólo deberían ocurrir cuando se " "importe explícitamente el sub-módulo." #: ../Doc/tutorial/modules.rst:500 msgid "" "The only solution is for the package author to provide an explicit index of " "the package. The :keyword:`import` statement uses the following convention: " "if a package's :file:`__init__.py` code defines a list named ``__all__``, it " "is taken to be the list of module names that should be imported when ``from " "package import *`` is encountered. It is up to the package author to keep " "this list up-to-date when a new version of the package is released. Package " "authors may also decide not to support it, if they don't see a use for " "importing \\* from their package. For example, the file :file:`sound/" "effects/__init__.py` could contain the following code::" msgstr "" "La única solución es que el autor del paquete provea un índice explícito del " "paquete. La declaración :keyword:`import` usa la siguiente convención: si " "el código del :file:`__init__.py` de un paquete define una lista llamada " "``__all__``, se toma como la lista de los nombres de módulos que deberían " "ser importados cuando se hace ``from package import *``. Es tarea del autor " "del paquete mantener actualizada esta lista cuando se libera una nueva " "versión del paquete. Los autores de paquetes podrían decidir no soportarlo, " "si no ven un uso para importar \\* en sus paquetes. Por ejemplo, el " "archivo :file:`sound/effects/__init__.py` podría contener el siguiente " "código::" #: ../Doc/tutorial/modules.rst:512 msgid "" "This would mean that ``from sound.effects import *`` would import the three " "named submodules of the :mod:`!sound.effects` package." msgstr "" "Esto significaría que ``from sound.effects import *`` importaría esos tres " "submódulos del paquete :mod:`!sound.effects`." #: ../Doc/tutorial/modules.rst:515 msgid "" "Be aware that submodules might become shadowed by locally defined names. For " "example, if you added a ``reverse`` function to the :file:`sound/effects/" "__init__.py` file, the ``from sound.effects import *`` would only import the " "two submodules ``echo`` and ``surround``, but *not* the ``reverse`` " "submodule, because it is shadowed by the locally defined ``reverse`` " "function::" msgstr "" "Ten en cuenta que los submódulos pueden quedar ocultos por nombres definidos " "localmente. Por ejemplo, si agregaste una función llamada ``reverse`` al " "archivo :file:`sound/effects/__init__.py`, ``from sound.effects import *`` " "solo importaría los dos submódulos ``echo`` y ``surround``, pero *no* el " "submódulo ``reverse`` porque queda oculto por la función ``reverse`` " "definida localmente::" #: ../Doc/tutorial/modules.rst:531 msgid "" "If ``__all__`` is not defined, the statement ``from sound.effects import *`` " "does *not* import all submodules from the package :mod:`!sound.effects` into " "the current namespace; it only ensures that the package :mod:`!sound." "effects` has been imported (possibly running any initialization code in :" "file:`__init__.py`) and then imports whatever names are defined in the " "package. This includes any names defined (and submodules explicitly loaded) " "by :file:`__init__.py`. It also includes any submodules of the package that " "were explicitly loaded by previous :keyword:`import` statements. Consider " "this code::" msgstr "" "Si no se define ``__all__``, la declaración ``from sound.effects import *`` " "*no* importa todos los submódulos del paquete :mod:`!sound.effects` al " "espacio de nombres actual; sólo se asegura que se haya importado el paquete :" "mod:`!sound.effects` (posiblemente ejecutando algún código de inicialización " "que haya en :file:`__init__.py`) y luego importa aquellos nombres que estén " "definidos en el paquete. Esto incluye cualquier nombre definido (y " "submódulos explícitamente cargados) por :file:`__init__.py`. También incluye " "cualquier submódulo del paquete que pudiera haber sido explícitamente " "cargado por declaraciones :keyword:`import` previas. Considere este código::" #: ../Doc/tutorial/modules.rst:544 msgid "" "In this example, the :mod:`!echo` and :mod:`!surround` modules are imported " "in the current namespace because they are defined in the :mod:`!sound." "effects` package when the ``from...import`` statement is executed. (This " "also works when ``__all__`` is defined.)" msgstr "" "En este ejemplo, los módulos :mod:`!echo` y :mod:`!surround` se importan en " "el espacio de nombre actual porque están definidos en el paquete :mod:`!" "sound.effects` cuando se ejecuta la declaración ``from...import``. (Esto " "también funciona cuando se define ``__all__``)." #: ../Doc/tutorial/modules.rst:549 msgid "" "Although certain modules are designed to export only names that follow " "certain patterns when you use ``import *``, it is still considered bad " "practice in production code." msgstr "" "A pesar de que ciertos módulos están diseñados para exportar solo nombres " "que siguen ciertos patrones cuando uses ``import *``, también se considera " "una mala práctica en código de producción." #: ../Doc/tutorial/modules.rst:553 msgid "" "Remember, there is nothing wrong with using ``from package import " "specific_submodule``! In fact, this is the recommended notation unless the " "importing module needs to use submodules with the same name from different " "packages." msgstr "" "Recuerda, ¡no hay nada malo al usar ``from package import " "specific_submodule``! De hecho, esta es la notación recomendada a menos que " "el módulo que importamos necesite usar submódulos con el mismo nombre desde " "un paquete diferente." #: ../Doc/tutorial/modules.rst:562 msgid "Intra-package References" msgstr "Referencias internas en paquetes" #: ../Doc/tutorial/modules.rst:564 msgid "" "When packages are structured into subpackages (as with the :mod:`!sound` " "package in the example), you can use absolute imports to refer to submodules " "of siblings packages. For example, if the module :mod:`!sound.filters." "vocoder` needs to use the :mod:`!echo` module in the :mod:`!sound.effects` " "package, it can use ``from sound.effects import echo``." msgstr "" "Cuando se estructuran los paquetes en sub-paquetes (como en el ejemplo :mod:" "`!sound`), puedes usar imports absolutos para referirte a submódulos de " "paquetes hermanos. Por ejemplo, si el módulo :mod:`!sound.filters.vocoder` " "necesita usar el módulo :mod:`!echo` en el paquete :mod:`!sound.effects`, " "puede hacer ``from sound.effects import echo``." #: ../Doc/tutorial/modules.rst:570 msgid "" "You can also write relative imports, with the ``from module import name`` " "form of import statement. These imports use leading dots to indicate the " "current and parent packages involved in the relative import. From the :mod:" "`!surround` module for example, you might use::" msgstr "" "También puedes escribir imports relativos con la forma ``from module import " "name``. Estos imports usan puntos adelante para indicar los paquetes " "actuales o paquetes padres involucrados en el import relativo. En el " "ejemplo :mod:`!surround`, podrías hacer::" #: ../Doc/tutorial/modules.rst:579 msgid "" "Note that relative imports are based on the name of the current module. " "Since the name of the main module is always ``\"__main__\"``, modules " "intended for use as the main module of a Python application must always use " "absolute imports." msgstr "" "Nótese que los imports relativos se basan en el nombre del módulo actual. Ya " "que el nombre del módulo principal es siempre ``\"__main__\"``, los módulos " "pensados para usarse como módulo principal de una aplicación Python siempre " "deberían usar ``import`` absolutos." #: ../Doc/tutorial/modules.rst:585 msgid "Packages in Multiple Directories" msgstr "Paquetes en múltiples directorios" #: ../Doc/tutorial/modules.rst:587 msgid "" "Packages support one more special attribute, :attr:`__path__`. This is " "initialized to be a list containing the name of the directory holding the " "package's :file:`__init__.py` before the code in that file is executed. " "This variable can be modified; doing so affects future searches for modules " "and subpackages contained in the package." msgstr "" "Los paquetes soportan un atributo especial más, :attr:`__path__`. Este se " "inicializa a una lista que contiene el nombre del directorio donde está el " "archivo :file:`__init__.py` del paquete, antes de que el código en ese " "archivo se ejecute. Esta variable puede modificarse, afectando búsquedas " "futuras de módulos y subpaquetes contenidos en el paquete." #: ../Doc/tutorial/modules.rst:593 msgid "" "While this feature is not often needed, it can be used to extend the set of " "modules found in a package." msgstr "" "Aunque esta característica no se necesita frecuentemente, puede usarse para " "extender el conjunto de módulos que se encuentran en el paquete." #: ../Doc/tutorial/modules.rst:598 msgid "Footnotes" msgstr "Notas al pie" #: ../Doc/tutorial/modules.rst:599 msgid "" "In fact function definitions are also 'statements' that are 'executed'; the " "execution of a module-level function definition adds the function name to " "the module's global namespace." msgstr "" "De hecho, las definiciones de funciones también son \"declaraciones\" que se " "\"ejecutan\"; la ejecución de una definición de función a nivel de módulo, " "añade el nombre de la función en el espacio de nombres global del módulo." #: ../Doc/tutorial/modules.rst:184 ../Doc/tutorial/modules.rst:267 #: ../Doc/tutorial/modules.rst:348 msgid "module" msgstr "module" #: ../Doc/tutorial/modules.rst:184 msgid "search" msgstr "search" #: ../Doc/tutorial/modules.rst:184 msgid "path" msgstr "path" #: ../Doc/tutorial/modules.rst:267 msgid "sys" msgstr "sys" #: ../Doc/tutorial/modules.rst:348 msgid "builtins" msgstr "builtins" #: ../Doc/tutorial/modules.rst:492 msgid "__all__" msgstr "__all__"