# 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: 2021-10-22 14:43+0100\n" "Last-Translator: Claudia Millan \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/faq/design.rst:3 msgid "Design and History FAQ" msgstr "Preguntas frecuentes sobre diseño e historia" #: ../Doc/faq/design.rst:6 msgid "Contents" msgstr "Contenido" #: ../Doc/faq/design.rst:11 msgid "Why does Python use indentation for grouping of statements?" msgstr "¿Por qué Python usa indentación para agrupar declaraciones?" #: ../Doc/faq/design.rst:13 msgid "" "Guido van Rossum believes that using indentation for grouping is extremely " "elegant and contributes a lot to the clarity of the average Python program. " "Most people learn to love this feature after a while." msgstr "" "Guido van Rossum cree que usar indentación para agrupar es extremadamente " "elegante y contribuye mucho a la claridad del programa Python promedio. La " "mayoría de las personas aprenden a amar esta característica después de un " "tiempo." #: ../Doc/faq/design.rst:17 msgid "" "Since there are no begin/end brackets there cannot be a disagreement between " "grouping perceived by the parser and the human reader. Occasionally C " "programmers will encounter a fragment of code like this::" msgstr "" "Como no hay corchetes de inicio/fin, no puede haber un desacuerdo entre la " "agrupación percibida por el analizador y el lector humano. Ocasionalmente, " "los programadores de C encontrarán un fragmento de código como este::" #: ../Doc/faq/design.rst:26 msgid "" "Only the ``x++`` statement is executed if the condition is true, but the " "indentation leads many to believe otherwise. Even experienced C programmers " "will sometimes stare at it a long time wondering as to why ``y`` is being " "decremented even for ``x > y``." msgstr "" "Solo se ejecuta la instrucción ``x ++`` si la condición es verdadera, pero " "la indentación lo lleva a creer lo contrario. Incluso los programadores " "experimentados de C a veces lo miran durante mucho tiempo preguntándose por " "qué ``y`` se está disminuyendo incluso para ``x > y``." #: ../Doc/faq/design.rst:31 msgid "" "Because there are no begin/end brackets, Python is much less prone to coding-" "style conflicts. In C there are many different ways to place the braces. " "After becoming used to reading and writing code using a particular style, it " "is normal to feel somewhat uneasy when reading (or being required to write) " "in a different one." msgstr "" "Debido a que no hay corchetes de inicio/fin, Python es mucho menos propenso " "a conflictos de estilo de codificación. En C hay muchas formas diferentes de " "colocar llaves. Después de acostumbrarse a leer y escribir código usando un " "estilo en particular, es normal sentirse algo incómodo al leer (o tener que " "escribir) en uno diferente." #: ../Doc/faq/design.rst:38 msgid "" "Many coding styles place begin/end brackets on a line by themselves. This " "makes programs considerably longer and wastes valuable screen space, making " "it harder to get a good overview of a program. Ideally, a function should " "fit on one screen (say, 20--30 lines). 20 lines of Python can do a lot more " "work than 20 lines of C. This is not solely due to the lack of begin/end " "brackets -- the lack of declarations and the high-level data types are also " "responsible -- but the indentation-based syntax certainly helps." msgstr "" "Muchos estilos de codificación colocan corchetes de inicio / fin en una " "línea por sí mismos. Esto hace que los programas sean considerablemente más " "largos y desperdicia un valioso espacio en la pantalla, lo que dificulta " "obtener una buena visión general de un programa. Idealmente, una función " "debería caber en una pantalla (por ejemplo, 20-30 líneas). 20 líneas de " "Python pueden hacer mucho más trabajo que 20 líneas de C. Esto no se debe " "únicamente a la falta de corchetes de inicio/fin -- la falta de " "declaraciones y los tipos de datos de alto nivel también son responsables -- " "sino también la indentación basada en la sintaxis ciertamente ayuda." #: ../Doc/faq/design.rst:48 msgid "Why am I getting strange results with simple arithmetic operations?" msgstr "" "¿Por qué obtengo resultados extraños con operaciones aritméticas simples?" #: ../Doc/faq/design.rst:50 msgid "See the next question." msgstr "Ver la siguiente pregunta." #: ../Doc/faq/design.rst:54 msgid "Why are floating-point calculations so inaccurate?" msgstr "¿Por qué los cálculos de punto flotante son tan inexactos?" #: ../Doc/faq/design.rst:56 msgid "Users are often surprised by results like this::" msgstr "Los usuarios a menudo se sorprenden por resultados como este::" #: ../Doc/faq/design.rst:61 msgid "" "and think it is a bug in Python. It's not. This has little to do with " "Python, and much more to do with how the underlying platform handles " "floating-point numbers." msgstr "" "y creo que es un error en Python. No es. Esto tiene poco que ver con Python, " "y mucho más con la forma en que la plataforma subyacente maneja los números " "de punto flotante." #: ../Doc/faq/design.rst:65 msgid "" "The :class:`float` type in CPython uses a C ``double`` for storage. A :" "class:`float` object's value is stored in binary floating-point with a fixed " "precision (typically 53 bits) and Python uses C operations, which in turn " "rely on the hardware implementation in the processor, to perform floating-" "point operations. This means that as far as floating-point operations are " "concerned, Python behaves like many popular languages including C and Java." msgstr "" "El tipo :class:`float` en CPython usa una C ``double`` para el " "almacenamiento. Un valor del objeto :class:`float` se almacena en coma " "flotante binaria con una precisión fija (típicamente 53 bits) y Python usa " "operaciones C, que a su vez dependen de la implementación de hardware en el " "procesador, para realizar operaciones de coma flotante. Esto significa que, " "en lo que respecta a las operaciones de punto flotante, Python se comporta " "como muchos lenguajes populares, incluidos C y Java." #: ../Doc/faq/design.rst:72 msgid "" "Many numbers that can be written easily in decimal notation cannot be " "expressed exactly in binary floating-point. For example, after::" msgstr "" "Muchos números que se pueden escribir fácilmente en notación decimal no se " "pueden expresar exactamente en coma flotante binaria. Por ejemplo, después " "de::" #: ../Doc/faq/design.rst:77 msgid "" "the value stored for ``x`` is a (very good) approximation to the decimal " "value ``1.2``, but is not exactly equal to it. On a typical machine, the " "actual stored value is::" msgstr "" "el valor almacenado para ``x`` es una aproximación (muy buena) al valor " "decimal ``1.2``, pero no es exactamente igual a él. En una máquina típica, " "el valor real almacenado es::" #: ../Doc/faq/design.rst:83 msgid "which is exactly::" msgstr "que es exactamente::" #: ../Doc/faq/design.rst:87 msgid "" "The typical precision of 53 bits provides Python floats with 15--16 decimal " "digits of accuracy." msgstr "" "La precisión típica de 53 bits proporciona flotantes Python con 15--16 " "dígitos decimales de precisión." #: ../Doc/faq/design.rst:90 msgid "" "For a fuller explanation, please see the :ref:`floating point arithmetic " "` chapter in the Python tutorial." msgstr "" "Para obtener una explicación más completa, consulte el capítulo :ref:" "`aritmética de coma flotante ` en el tutorial de Python." #: ../Doc/faq/design.rst:95 msgid "Why are Python strings immutable?" msgstr "¿Por qué las cadenas de caracteres de Python son inmutables?" #: ../Doc/faq/design.rst:97 msgid "There are several advantages." msgstr "Hay varias ventajas." #: ../Doc/faq/design.rst:99 msgid "" "One is performance: knowing that a string is immutable means we can allocate " "space for it at creation time, and the storage requirements are fixed and " "unchanging. This is also one of the reasons for the distinction between " "tuples and lists." msgstr "" "Una es el rendimiento: saber que una cadena es inmutable significa que " "podemos asignarle espacio en el momento de la creación, y los requisitos de " "almacenamiento son fijos e inmutables. Esta es también una de las razones " "para la distinción entre tuplas y listas." #: ../Doc/faq/design.rst:104 msgid "" "Another advantage is that strings in Python are considered as \"elemental\" " "as numbers. No amount of activity will change the value 8 to anything else, " "and in Python, no amount of activity will change the string \"eight\" to " "anything else." msgstr "" "Otra ventaja es que las cadenas en Python se consideran tan \"elementales\" " "como los números. Ninguna cantidad de actividad cambiará el valor 8 a otra " "cosa, y en Python, ninguna cantidad de actividad cambiará la cadena \"ocho\" " "a otra cosa." #: ../Doc/faq/design.rst:112 msgid "Why must 'self' be used explicitly in method definitions and calls?" msgstr "" "¿Por qué debe usarse 'self' explícitamente en las definiciones y llamadas de " "métodos?" #: ../Doc/faq/design.rst:114 msgid "" "The idea was borrowed from Modula-3. It turns out to be very useful, for a " "variety of reasons." msgstr "" "La idea fue tomada de Modula-3. Resulta ser muy útil, por una variedad de " "razones." #: ../Doc/faq/design.rst:117 msgid "" "First, it's more obvious that you are using a method or instance attribute " "instead of a local variable. Reading ``self.x`` or ``self.meth()`` makes it " "absolutely clear that an instance variable or method is used even if you " "don't know the class definition by heart. In C++, you can sort of tell by " "the lack of a local variable declaration (assuming globals are rare or " "easily recognizable) -- but in Python, there are no local variable " "declarations, so you'd have to look up the class definition to be sure. " "Some C++ and Java coding standards call for instance attributes to have an " "``m_`` prefix, so this explicitness is still useful in those languages, too." msgstr "" "Primero, es más obvio que está utilizando un método o atributo de instancia " "en lugar de una variable local. Leer ``self.x`` o ``self.meth()`` deja " "absolutamente claro que se usa una variable de instancia o método incluso si " "no conoce la definición de clase de memoria. En C++, puede darse cuenta de " "la falta de una declaración de variable local (suponiendo que los globales " "son raros o fácilmente reconocibles) -- pero en Python, no hay declaraciones " "de variables locales, por lo que debería buscar la definición de clase para " "estar seguro. Algunos estándares de codificación de C++ y Java requieren que " "los atributos de instancia tengan un prefijo ``m_``, porque el ser explícito " "también es útil en esos lenguajes." #: ../Doc/faq/design.rst:127 msgid "" "Second, it means that no special syntax is necessary if you want to " "explicitly reference or call the method from a particular class. In C++, if " "you want to use a method from a base class which is overridden in a derived " "class, you have to use the ``::`` operator -- in Python you can write " "``baseclass.methodname(self, )``. This is particularly " "useful for :meth:`__init__` methods, and in general in cases where a derived " "class method wants to extend the base class method of the same name and thus " "has to call the base class method somehow." msgstr "" "En segundo lugar, significa que no es necesaria una sintaxis especial si " "desea hacer referencia explícita o llamar al método desde una clase en " "particular. En C++, si desea usar un método de una clase base que se anula " "en una clase derivada, debe usar el operador ``::`` -- en Python puede " "escribir ``baseclass.methodname(self, )``. Esto es " "particularmente útil para métodos :meth:`__init__`, y en general en los " "casos en que un método de clase derivada quiere extender el método de clase " "base del mismo nombre y, por lo tanto, tiene que llamar al método de clase " "base de alguna manera." #: ../Doc/faq/design.rst:136 msgid "" "Finally, for instance variables it solves a syntactic problem with " "assignment: since local variables in Python are (by definition!) those " "variables to which a value is assigned in a function body (and that aren't " "explicitly declared global), there has to be some way to tell the " "interpreter that an assignment was meant to assign to an instance variable " "instead of to a local variable, and it should preferably be syntactic (for " "efficiency reasons). C++ does this through declarations, but Python doesn't " "have declarations and it would be a pity having to introduce them just for " "this purpose. Using the explicit ``self.var`` solves this nicely. " "Similarly, for using instance variables, having to write ``self.var`` means " "that references to unqualified names inside a method don't have to search " "the instance's directories. To put it another way, local variables and " "instance variables live in two different namespaces, and you need to tell " "Python which namespace to use." msgstr "" "Finalmente, para las variables de instancia se resuelve un problema " "sintáctico con la asignación: dado que las variables locales en Python son " "(¡por definición!) Aquellas variables a las que se asigna un valor en un " "cuerpo de función (y que no se declaran explícitamente como globales), tiene " "que haber una forma de decirle al intérprete que una asignación estaba " "destinada a asignar a una variable de instancia en lugar de a una variable " "local, y que preferiblemente debería ser sintáctica (por razones de " "eficiencia). C++ hace esto a través de declaraciones, pero Python no tiene " "declaraciones y sería una pena tener que presentarlas solo para este " "propósito. Usar el ``self.var`` explícito resuelve esto muy bien. Del mismo " "modo, para usar variables de instancia, tener que escribir ``self.var`` " "significa que las referencias a nombres no calificados dentro de un método " "no tienen que buscar en los directorios de la instancia. Para decirlo de " "otra manera, las variables locales y las variables de instancia viven en dos " "espacios de nombres diferentes, y debe decirle a Python qué espacio de " "nombres usar." #: ../Doc/faq/design.rst:154 msgid "Why can't I use an assignment in an expression?" msgstr "¿Por qué no puedo usar una tarea en una expresión?" #: ../Doc/faq/design.rst:156 msgid "Starting in Python 3.8, you can!" msgstr "¡A partir de Python 3.8, se puede!" #: ../Doc/faq/design.rst:158 #, fuzzy msgid "" "Assignment expressions using the walrus operator ``:=`` assign a variable in " "an expression::" msgstr "" "Asignación de expresiones usando el operador de morsa `:=` asigna una " "variable en una expresión::" #: ../Doc/faq/design.rst:164 msgid "See :pep:`572` for more information." msgstr "Ver :pep:`572` para más información." #: ../Doc/faq/design.rst:169 msgid "" "Why does Python use methods for some functionality (e.g. list.index()) but " "functions for other (e.g. len(list))?" msgstr "" "¿Por qué Python usa métodos para alguna funcionalidad (por ejemplo, list." "index()) pero funciones para otra (por ejemplo, len(list))?" #: ../Doc/faq/design.rst:171 msgid "As Guido said:" msgstr "Como dijo Guido:" #: ../Doc/faq/design.rst:173 msgid "" "(a) For some operations, prefix notation just reads better than postfix -- " "prefix (and infix!) operations have a long tradition in mathematics which " "likes notations where the visuals help the mathematician thinking about a " "problem. Compare the easy with which we rewrite a formula like x*(a+b) into " "x*a + x*b to the clumsiness of doing the same thing using a raw OO notation." msgstr "" "(a) Para algunas operaciones, la notación de prefijo solo se lee mejor que " "postfijo -- las operaciones de prefijo (e ¡infijo!) tienen una larga " "tradición en matemáticas que le gustan las anotaciones donde las imágenes " "ayudan al matemático a pensar en un problema. Compare lo fácil con que " "reescribimos una fórmula como x*(a+b) en x*a + x*b con la torpeza de hacer " "lo mismo usando una notación OO sin procesar." #: ../Doc/faq/design.rst:180 msgid "" "(b) When I read code that says len(x) I *know* that it is asking for the " "length of something. This tells me two things: the result is an integer, and " "the argument is some kind of container. To the contrary, when I read x." "len(), I have to already know that x is some kind of container implementing " "an interface or inheriting from a class that has a standard len(). Witness " "the confusion we occasionally have when a class that is not implementing a " "mapping has a get() or keys() method, or something that isn't a file has a " "write() method." msgstr "" "(b) Cuando leo un código que dice len(x), *sé* que está pidiendo la longitud " "de algo. Esto me dice dos cosas: el resultado es un número entero y el " "argumento es algún tipo de contenedor. Por el contrario, cuando leo x.len " "(), ya debo saber que x es algún tipo de contenedor que implementa una " "interfaz o hereda de una clase que tiene un estándar len(). Sea testigo de " "la confusión que ocasionalmente tenemos cuando una clase que no está " "implementando una asignación tiene un método get() o keys(), o algo que no " "es un archivo tiene un método write()." #: ../Doc/faq/design.rst:207 msgid "https://mail.python.org/pipermail/python-3000/2006-November/004643.html" msgstr "" "https://mail.python.org/pipermail/python-3000/2006-November/004643.html" #: ../Doc/faq/design.rst:193 msgid "Why is join() a string method instead of a list or tuple method?" msgstr "" "¿Por qué join() es un método de cadena de caracteres en lugar de un método " "de lista o tupla?" #: ../Doc/faq/design.rst:195 msgid "" "Strings became much more like other standard types starting in Python 1.6, " "when methods were added which give the same functionality that has always " "been available using the functions of the string module. Most of these new " "methods have been widely accepted, but the one which appears to make some " "programmers feel uncomfortable is::" msgstr "" "Las cadenas de caracteres se volvieron mucho más parecidas a otros tipos " "estándar a partir de Python 1.6, cuando se agregaron métodos que brindan la " "misma funcionalidad que siempre ha estado disponible utilizando las " "funciones del módulo de cadenas. La mayoría de estos nuevos métodos han sido " "ampliamente aceptados, pero el que parece hacer que algunos programadores se " "sientan incómodos es:" #: ../Doc/faq/design.rst:203 msgid "which gives the result::" msgstr "que da el resultado::" #: ../Doc/faq/design.rst:207 msgid "There are two common arguments against this usage." msgstr "Hay dos argumentos comunes en contra de este uso." #: ../Doc/faq/design.rst:209 msgid "" "The first runs along the lines of: \"It looks really ugly using a method of " "a string literal (string constant)\", to which the answer is that it might, " "but a string literal is just a fixed value. If the methods are to be allowed " "on names bound to strings there is no logical reason to make them " "unavailable on literals." msgstr "" "El primero corre a lo largo de las líneas de: \"Se ve realmente feo el uso " "de un método de un literal de cadena (constante de cadena)\", a lo que la " "respuesta es que sí, pero un literal de cadena es solo un valor fijo. Si se " "permiten los métodos en nombres vinculados a cadenas, no hay razón lógica " "para que no estén disponibles en literales." #: ../Doc/faq/design.rst:215 msgid "" "The second objection is typically cast as: \"I am really telling a sequence " "to join its members together with a string constant\". Sadly, you aren't. " "For some reason there seems to be much less difficulty with having :meth:" "`~str.split` as a string method, since in that case it is easy to see that ::" msgstr "" "La segunda objeción generalmente se presenta como: \"Realmente estoy " "diciéndole a una secuencia que una a sus miembros junto con una constante de " "cadena\". Lamentablemente, no lo estas haciendo. Por alguna razón, parece " "ser mucho menos difícil tener :meth:`~str.split` como método de cadena, ya " "que en ese caso es fácil ver que::" #: ../Doc/faq/design.rst:222 msgid "" "is an instruction to a string literal to return the substrings delimited by " "the given separator (or, by default, arbitrary runs of white space)." msgstr "" "es una instrucción a un literal de cadena para retornar las subcadenas de " "caracteres delimitadas por el separador dado (o, por defecto, ejecuciones " "arbitrarias de espacio en blanco)." #: ../Doc/faq/design.rst:225 msgid "" ":meth:`~str.join` is a string method because in using it you are telling the " "separator string to iterate over a sequence of strings and insert itself " "between adjacent elements. This method can be used with any argument which " "obeys the rules for sequence objects, including any new classes you might " "define yourself. Similar methods exist for bytes and bytearray objects." msgstr "" ":meth:`~str.join` es un método de cadena de caracteres porque al usarlo le " "está diciendo a la cadena de separación que itere sobre una secuencia de " "cadenas y se inserte entre elementos adyacentes. Este método se puede usar " "con cualquier argumento que obedezca las reglas para los objetos de " "secuencia, incluidas las clases nuevas que pueda definir usted mismo. " "Existen métodos similares para bytes y objetos bytearray." #: ../Doc/faq/design.rst:233 msgid "How fast are exceptions?" msgstr "¿Qué tan rápido van las excepciones?" #: ../Doc/faq/design.rst:235 msgid "" "A try/except block is extremely efficient if no exceptions are raised. " "Actually catching an exception is expensive. In versions of Python prior to " "2.0 it was common to use this idiom::" msgstr "" "Un bloque try/except es extremadamente eficiente si no se generan " "excepciones. En realidad, capturar una excepción es costoso. En versiones de " "Python anteriores a la 2.0, era común usar este modismo::" #: ../Doc/faq/design.rst:245 msgid "" "This only made sense when you expected the dict to have the key almost all " "the time. If that wasn't the case, you coded it like this::" msgstr "" "Esto solo tenía sentido cuando esperaba que el dict tuviera la clave casi " "todo el tiempo. Si ese no fuera el caso, lo codificó así:" #: ../Doc/faq/design.rst:253 msgid "" "For this specific case, you could also use ``value = dict.setdefault(key, " "getvalue(key))``, but only if the ``getvalue()`` call is cheap enough " "because it is evaluated in all cases." msgstr "" "Para este caso específico, también podría usar ``value = dict." "setdefault(key, getvalue(key))``, pero solo si la llamada ``getvalue()`` es " "lo suficientemente barata porque se evalúa en todos los casos." #: ../Doc/faq/design.rst:259 msgid "Why isn't there a switch or case statement in Python?" msgstr "¿Por qué no hay un *switch* o una declaración *case* en Python?" #: ../Doc/faq/design.rst:261 msgid "" "You can do this easily enough with a sequence of ``if... elif... elif... " "else``. For literal values, or constants within a namespace, you can also " "use a ``match ... case`` statement." msgstr "" "Puede hacer esto con bastante facilidad con una secuencia de ``if... " "elif... elif... else``. Para valores literales, o constantes dentro de un " "espacio de nombres, también puede usar una declaración ``match ... case``." #: ../Doc/faq/design.rst:265 msgid "" "For cases where you need to choose from a very large number of " "possibilities, you can create a dictionary mapping case values to functions " "to call. For example::" msgstr "" "Para los casos en los que necesita elegir entre una gran cantidad de " "posibilidades, puede crear un diccionario que asigne valores de casos a " "funciones para llamar. Por ejemplo::" #: ../Doc/faq/design.rst:276 msgid "" "For calling methods on objects, you can simplify yet further by using the :" "func:`getattr` built-in to retrieve methods with a particular name::" msgstr "" "Para invocar métodos en objetos, puede simplificar aún más utilizando :func:" "`getattr` incorporado para recuperar métodos con un nombre particular::" #: ../Doc/faq/design.rst:288 msgid "" "It's suggested that you use a prefix for the method names, such as " "``visit_`` in this example. Without such a prefix, if values are coming " "from an untrusted source, an attacker would be able to call any method on " "your object." msgstr "" "Se sugiere que utilice un prefijo para los nombres de los métodos, como " "``visit_`` en este ejemplo. Sin dicho prefijo, si los valores provienen de " "una fuente no confiable, un atacante podría invocar cualquier método en su " "objeto." #: ../Doc/faq/design.rst:294 msgid "" "Can't you emulate threads in the interpreter instead of relying on an OS-" "specific thread implementation?" msgstr "" "¿No puede emular hilos en el intérprete en lugar de confiar en una " "implementación de hilos específica del sistema operativo?" #: ../Doc/faq/design.rst:296 msgid "" "Answer 1: Unfortunately, the interpreter pushes at least one C stack frame " "for each Python stack frame. Also, extensions can call back into Python at " "almost random moments. Therefore, a complete threads implementation " "requires thread support for C." msgstr "" "Respuesta 1: Desafortunadamente, el intérprete empuja al menos un marco de " "pila C para cada marco de pila de Python. Además, las extensiones pueden " "volver a llamar a Python en momentos casi aleatorios. Por lo tanto, una " "implementación completa de subprocesos requiere soporte de subprocesos para " "C." #: ../Doc/faq/design.rst:301 msgid "" "Answer 2: Fortunately, there is `Stackless Python `_, which has a completely redesigned " "interpreter loop that avoids the C stack." msgstr "" "Respuesta 2: Afortunadamente, existe `Python sin pila `_, que tiene un bucle de intérprete " "completamente rediseñado que evita la pila C." #: ../Doc/faq/design.rst:306 msgid "Why can't lambda expressions contain statements?" msgstr "¿Por qué las expresiones lambda no pueden contener sentencias?" #: ../Doc/faq/design.rst:308 msgid "" "Python lambda expressions cannot contain statements because Python's " "syntactic framework can't handle statements nested inside expressions. " "However, in Python, this is not a serious problem. Unlike lambda forms in " "other languages, where they add functionality, Python lambdas are only a " "shorthand notation if you're too lazy to define a function." msgstr "" "Las expresiones lambda de Python no pueden contener declaraciones porque el " "marco sintáctico de Python no puede manejar declaraciones anidadas dentro de " "expresiones. Sin embargo, en Python, este no es un problema grave. A " "diferencia de las formas lambda en otros lenguajes, donde agregan " "funcionalidad, las lambdas de Python son solo una notación abreviada si eres " "demasiado vago para definir una función." #: ../Doc/faq/design.rst:314 #, fuzzy msgid "" "Functions are already first class objects in Python, and can be declared in " "a local scope. Therefore the only advantage of using a lambda instead of a " "locally defined function is that you don't need to invent a name for the " "function -- but that's just a local variable to which the function object " "(which is exactly the same type of object that a lambda expression yields) " "is assigned!" msgstr "" "Las funciones ya son objetos de primera clase en Python y pueden declararse " "en un ámbito local. Por lo tanto, la única ventaja de usar una lambda en " "lugar de una función definida localmente es que no es necesario inventar un " "nombre para la función, sino que es solo una variable local para la cual el " "objeto de función (que es exactamente el mismo tipo de se asigna un objeto " "que produce una expresión lambda)" #: ../Doc/faq/design.rst:322 msgid "Can Python be compiled to machine code, C or some other language?" msgstr "¿Se puede compilar Python en código máquina, C o algún otro lenguaje?" #: ../Doc/faq/design.rst:324 #, fuzzy msgid "" "`Cython `_ compiles a modified version of Python with " "optional annotations into C extensions. `Nuitka `_ " "is an up-and-coming compiler of Python into C++ code, aiming to support the " "full Python language." msgstr "" "`Cython `_ compila una versión modificada de Python con " "anotaciones opcionales en extensiones C. `Nuitka `_ " "es un compilador prometedor de Python en código C ++, con el objetivo de " "soportar el lenguaje completo de Python. Para compilar en Java puede " "considerar `VOC `_." #: ../Doc/faq/design.rst:331 msgid "How does Python manage memory?" msgstr "¿Cómo gestiona Python la memoria?" #: ../Doc/faq/design.rst:333 msgid "" "The details of Python memory management depend on the implementation. The " "standard implementation of Python, :term:`CPython`, uses reference counting " "to detect inaccessible objects, and another mechanism to collect reference " "cycles, periodically executing a cycle detection algorithm which looks for " "inaccessible cycles and deletes the objects involved. The :mod:`gc` module " "provides functions to perform a garbage collection, obtain debugging " "statistics, and tune the collector's parameters." msgstr "" "Los detalles de la administración de memoria de Python dependen de la " "implementación. La implementación estándar de Python, :term:`CPython`, " "utiliza el recuento de referencias para detectar objetos inaccesibles, y " "otro mecanismo para recopilar ciclos de referencia, ejecutando " "periódicamente un algoritmo de detección de ciclos que busca ciclos " "inaccesibles y elimina los objetos involucrados. El módulo :mod:`gc` " "proporciona funciones para realizar una recolección de basura, obtener " "estadísticas de depuración y ajustar los parámetros del recolector." #: ../Doc/faq/design.rst:341 #, fuzzy msgid "" "Other implementations (such as `Jython `_ or `PyPy " "`_), however, can rely on a different mechanism such " "as a full-blown garbage collector. This difference can cause some subtle " "porting problems if your Python code depends on the behavior of the " "reference counting implementation." msgstr "" "Sin embargo, otras implementaciones (como `Jython `_ " "o `PyPy `_) pueden confiar en un mecanismo diferente, " "como recolector de basura. Esta diferencia puede causar algunos problemas " "sutiles de portabilidad si su código de Python depende del comportamiento de " "la implementación de conteo de referencias." #: ../Doc/faq/design.rst:347 msgid "" "In some Python implementations, the following code (which is fine in " "CPython) will probably run out of file descriptors::" msgstr "" "En algunas implementaciones de Python, el siguiente código (que está bien en " "CPython) probablemente se quedará sin descriptores de archivo::" #: ../Doc/faq/design.rst:354 msgid "" "Indeed, using CPython's reference counting and destructor scheme, each new " "assignment to *f* closes the previous file. With a traditional GC, however, " "those file objects will only get collected (and closed) at varying and " "possibly long intervals." msgstr "" "De hecho, utilizando el esquema de conteo de referencias y destructor de " "CPython, cada nueva asignación a *f* cierra el archivo anterior. Sin " "embargo, con un GC tradicional, esos objetos de archivo solo se recopilarán " "(y cerrarán) a intervalos variables y posiblemente largos." #: ../Doc/faq/design.rst:359 msgid "" "If you want to write code that will work with any Python implementation, you " "should explicitly close the file or use the :keyword:`with` statement; this " "will work regardless of memory management scheme::" msgstr "" "Si desea escribir código que funcione con cualquier implementación de " "Python, debe cerrar explícitamente el archivo o utilizar una declaración :" "keyword:`with`; esto funcionará independientemente del esquema de " "administración de memoria::" #: ../Doc/faq/design.rst:369 msgid "Why doesn't CPython use a more traditional garbage collection scheme?" msgstr "" "¿Por qué CPython no utiliza un esquema de recolección de basura más " "tradicional?" #: ../Doc/faq/design.rst:371 msgid "" "For one thing, this is not a C standard feature and hence it's not portable. " "(Yes, we know about the Boehm GC library. It has bits of assembler code for " "*most* common platforms, not for all of them, and although it is mostly " "transparent, it isn't completely transparent; patches are required to get " "Python to work with it.)" msgstr "" "Por un lado, esta no es una característica estándar de C y, por lo tanto, no " "es portátil. (Sí, sabemos acerca de la biblioteca Boehm GC. Tiene fragmentos " "de código de ensamblador para *la mayoría* de las plataformas comunes, no " "para todas ellas, y aunque es principalmente transparente, no es " "completamente transparente; se requieren parches para obtener Python para " "trabajar con eso)" #: ../Doc/faq/design.rst:377 msgid "" "Traditional GC also becomes a problem when Python is embedded into other " "applications. While in a standalone Python it's fine to replace the " "standard malloc() and free() with versions provided by the GC library, an " "application embedding Python may want to have its *own* substitute for " "malloc() and free(), and may not want Python's. Right now, CPython works " "with anything that implements malloc() and free() properly." msgstr "" "El GC tradicional también se convierte en un problema cuando Python está " "integrado en otras aplicaciones. Mientras que en un Python independiente " "está bien reemplazar el estándar malloc() y free() con versiones " "proporcionadas por la biblioteca GC, una aplicación que incruste Python " "puede querer tener su *propio* sustituto de malloc() y free(), y puede No " "quiero a Python. En este momento, CPython funciona con todo lo que " "implementa malloc() y free() correctamente." #: ../Doc/faq/design.rst:386 msgid "Why isn't all memory freed when CPython exits?" msgstr "¿Por qué no se libera toda la memoria cuando sale CPython?" #: ../Doc/faq/design.rst:388 msgid "" "Objects referenced from the global namespaces of Python modules are not " "always deallocated when Python exits. This may happen if there are circular " "references. There are also certain bits of memory that are allocated by the " "C library that are impossible to free (e.g. a tool like Purify will complain " "about these). Python is, however, aggressive about cleaning up memory on " "exit and does try to destroy every single object." msgstr "" "Los objetos a los que se hace referencia desde los espacios de nombres " "globales de los módulos de Python no siempre se desasignan cuando Python " "sale. Esto puede suceder si hay referencias circulares. También hay ciertos " "bits de memoria asignados por la biblioteca de C que son imposibles de " "liberar (por ejemplo, una herramienta como Purify se quejará de estos). " "Python es, sin embargo, agresivo sobre la limpieza de la memoria al salir e " "intenta destruir cada objeto." #: ../Doc/faq/design.rst:395 msgid "" "If you want to force Python to delete certain things on deallocation use " "the :mod:`atexit` module to run a function that will force those deletions." msgstr "" "Si desea forzar a Python a eliminar ciertas cosas en la desasignación, use " "el módulo :mod:`atexit` para ejecutar una función que obligará a esas " "eliminaciones." #: ../Doc/faq/design.rst:400 msgid "Why are there separate tuple and list data types?" msgstr "¿Por qué hay tipos de datos separados de tuplas y listas?" #: ../Doc/faq/design.rst:402 msgid "" "Lists and tuples, while similar in many respects, are generally used in " "fundamentally different ways. Tuples can be thought of as being similar to " "Pascal records or C structs; they're small collections of related data which " "may be of different types which are operated on as a group. For example, a " "Cartesian coordinate is appropriately represented as a tuple of two or three " "numbers." msgstr "" "Las listas y las tuplas, si bien son similares en muchos aspectos, " "generalmente se usan de maneras fundamentalmente diferentes. Se puede pensar " "que las tuplas son similares a los registros Pascal o estructuras C; son " "pequeñas colecciones de datos relacionados que pueden ser de diferentes " "tipos que funcionan como un grupo. Por ejemplo, una coordenada cartesiana se " "representa adecuadamente como una tupla de dos o tres números." #: ../Doc/faq/design.rst:409 msgid "" "Lists, on the other hand, are more like arrays in other languages. They " "tend to hold a varying number of objects all of which have the same type and " "which are operated on one-by-one. For example, ``os.listdir('.')`` returns " "a list of strings representing the files in the current directory. " "Functions which operate on this output would generally not break if you " "added another file or two to the directory." msgstr "" "Las listas, por otro lado, son más como matrices en otros lenguajes. Tienden " "a contener un número variable de objetos, todos los cuales tienen el mismo " "tipo y que se operan uno por uno. Por ejemplo, ``os.listdir('.')`` Retorna " "una lista de cadenas de caracteres que representan los archivos en el " "directorio actual. Las funciones que operan en esta salida generalmente no " "se romperían si agregara otro archivo o dos al directorio." #: ../Doc/faq/design.rst:416 msgid "" "Tuples are immutable, meaning that once a tuple has been created, you can't " "replace any of its elements with a new value. Lists are mutable, meaning " "that you can always change a list's elements. Only immutable elements can " "be used as dictionary keys, and hence only tuples and not lists can be used " "as keys." msgstr "" "Las tuplas son inmutables, lo que significa que una vez que se ha creado una " "tupla, no puede reemplazar ninguno de sus elementos con un nuevo valor. Las " "listas son mutables, lo que significa que siempre puede cambiar los " "elementos de una lista. Solo los elementos inmutables se pueden usar como " "claves de diccionario y, por lo tanto, solo las tuplas y no las listas se " "pueden usar como claves." #: ../Doc/faq/design.rst:423 msgid "How are lists implemented in CPython?" msgstr "¿Cómo se implementan las listas en Python?" #: ../Doc/faq/design.rst:425 msgid "" "CPython's lists are really variable-length arrays, not Lisp-style linked " "lists. The implementation uses a contiguous array of references to other " "objects, and keeps a pointer to this array and the array's length in a list " "head structure." msgstr "" "Las listas de CPython son realmente matrices de longitud variable, no listas " "enlazadas al estilo Lisp. La implementación utiliza una matriz contigua de " "referencias a otros objetos y mantiene un puntero a esta matriz y la " "longitud de la matriz en una estructura de encabezado de lista." #: ../Doc/faq/design.rst:429 msgid "" "This makes indexing a list ``a[i]`` an operation whose cost is independent " "of the size of the list or the value of the index." msgstr "" "Esto hace que indexar una lista ``a[i]`` una operación cuyo costo es " "independiente del tamaño de la lista o del valor del índice." #: ../Doc/faq/design.rst:432 msgid "" "When items are appended or inserted, the array of references is resized. " "Some cleverness is applied to improve the performance of appending items " "repeatedly; when the array must be grown, some extra space is allocated so " "the next few times don't require an actual resize." msgstr "" "Cuando se añaden o insertan elementos, la matriz de referencias cambia de " "tamaño. Se aplica cierta inteligencia para mejorar el rendimiento de la " "adición de elementos repetidamente; cuando la matriz debe crecer, se asigna " "un espacio extra para que las próximas veces no requieran un cambio de " "tamaño real." #: ../Doc/faq/design.rst:439 msgid "How are dictionaries implemented in CPython?" msgstr "¿Cómo se implementan los diccionarios en CPython?" #: ../Doc/faq/design.rst:441 msgid "" "CPython's dictionaries are implemented as resizable hash tables. Compared " "to B-trees, this gives better performance for lookup (the most common " "operation by far) under most circumstances, and the implementation is " "simpler." msgstr "" "Los diccionarios de CPython se implementan como tablas hash " "redimensionables. En comparación con los árboles B (*B-trees*), esto " "proporciona un mejor rendimiento para la búsqueda (la operación más común " "con diferencia) en la mayoría de las circunstancias, y la implementación es " "más simple." #: ../Doc/faq/design.rst:445 msgid "" "Dictionaries work by computing a hash code for each key stored in the " "dictionary using the :func:`hash` built-in function. The hash code varies " "widely depending on the key and a per-process seed; for example, \"Python\" " "could hash to -539294296 while \"python\", a string that differs by a single " "bit, could hash to 1142331976. The hash code is then used to calculate a " "location in an internal array where the value will be stored. Assuming that " "you're storing keys that all have different hash values, this means that " "dictionaries take constant time -- O(1), in Big-O notation -- to retrieve a " "key." msgstr "" "Los diccionarios funcionan calculando un código hash para cada clave " "almacenada en el diccionario utilizando la función incorporada :func:`hash`. " "El código hash varía ampliamente según la clave y una semilla por proceso; " "por ejemplo, \"Python\" podría dividir en hash a -539294296 mientras que " "\"python\", una cadena que difiere en un solo bit, podría dividir en " "1142331976. El código de resumen se usa para calcular una ubicación en una " "matriz interna donde se almacenará el valor . Suponiendo que está " "almacenando claves que tienen valores hash diferentes, esto significa que " "los diccionarios toman tiempo constante -- O(1), en notación Big-O -- para " "recuperar una clave." #: ../Doc/faq/design.rst:456 msgid "Why must dictionary keys be immutable?" msgstr "¿Por qué las claves del diccionario deben ser inmutables?" #: ../Doc/faq/design.rst:458 msgid "" "The hash table implementation of dictionaries uses a hash value calculated " "from the key value to find the key. If the key were a mutable object, its " "value could change, and thus its hash could also change. But since whoever " "changes the key object can't tell that it was being used as a dictionary " "key, it can't move the entry around in the dictionary. Then, when you try " "to look up the same object in the dictionary it won't be found because its " "hash value is different. If you tried to look up the old value it wouldn't " "be found either, because the value of the object found in that hash bin " "would be different." msgstr "" "La implementación de la tabla hash de los diccionarios utiliza un valor hash " "calculado a partir del valor clave para encontrar la clave. Si la clave " "fuera un objeto mutable, su valor podría cambiar y, por lo tanto, su hash " "también podría cambiar. Pero dado que quien cambie el objeto clave no puede " "decir que se estaba utilizando como clave de diccionario, no puede mover la " "entrada en el diccionario. Luego, cuando intente buscar el mismo objeto en " "el diccionario, no se encontrará porque su valor hash es diferente. Si trató " "de buscar el valor anterior, tampoco lo encontraría, porque el valor del " "objeto que se encuentra en ese hash bin sería diferente." #: ../Doc/faq/design.rst:467 msgid "" "If you want a dictionary indexed with a list, simply convert the list to a " "tuple first; the function ``tuple(L)`` creates a tuple with the same entries " "as the list ``L``. Tuples are immutable and can therefore be used as " "dictionary keys." msgstr "" "Si desea un diccionario indexado con una lista, simplemente convierta la " "lista a una tupla primero; La función ``tuple(L)`` crea una tupla con las " "mismas entradas que la lista ``L``. Las tuplas son inmutables y, por lo " "tanto, pueden usarse como claves de diccionario." #: ../Doc/faq/design.rst:471 msgid "Some unacceptable solutions that have been proposed:" msgstr "Algunas soluciones inaceptables que se han propuesto:" #: ../Doc/faq/design.rst:473 msgid "" "Hash lists by their address (object ID). This doesn't work because if you " "construct a new list with the same value it won't be found; e.g.::" msgstr "" "Listas de hash por su dirección (ID de objeto). Esto no funciona porque si " "construye una nueva lista con el mismo valor, no se encontrará; por ejemplo::" #: ../Doc/faq/design.rst:479 msgid "" "would raise a :exc:`KeyError` exception because the id of the ``[1, 2]`` " "used in the second line differs from that in the first line. In other " "words, dictionary keys should be compared using ``==``, not using :keyword:" "`is`." msgstr "" "generaría una excepción :exc:`KeyError` porque la identificación del ``[1, " "2]`` usado en la segunda línea difiere de la de la primera línea. En otras " "palabras, las claves del diccionario deben compararse usando ``==``, no " "usando :keyword:`is`." #: ../Doc/faq/design.rst:483 msgid "" "Make a copy when using a list as a key. This doesn't work because the list, " "being a mutable object, could contain a reference to itself, and then the " "copying code would run into an infinite loop." msgstr "" "Hacer una copia cuando use una lista como clave. Esto no funciona porque la " "lista, al ser un objeto mutable, podría contener una referencia a sí misma, " "y luego el código de copia se ejecutaría en un bucle infinito." #: ../Doc/faq/design.rst:487 msgid "" "Allow lists as keys but tell the user not to modify them. This would allow " "a class of hard-to-track bugs in programs when you forgot or modified a list " "by accident. It also invalidates an important invariant of dictionaries: " "every value in ``d.keys()`` is usable as a key of the dictionary." msgstr "" "Permitir listas como claves pero decirle al usuario que no las modifique. " "Esto permitiría una clase de errores difíciles de rastrear en los programas " "cuando olvidó o modificó una lista por accidente. También invalida una " "invariante importante de diccionarios: cada valor en ``d.keys()`` se puede " "usar como una clave del diccionario." #: ../Doc/faq/design.rst:492 msgid "" "Mark lists as read-only once they are used as a dictionary key. The problem " "is that it's not just the top-level object that could change its value; you " "could use a tuple containing a list as a key. Entering anything as a key " "into a dictionary would require marking all objects reachable from there as " "read-only -- and again, self-referential objects could cause an infinite " "loop." msgstr "" "Marcar las listas como de solo lectura una vez que se usan como clave de " "diccionario. El problema es que no solo el objeto de nivel superior puede " "cambiar su valor; podría usar una tupla que contiene una lista como clave. " "Ingresar cualquier cosa como clave en un diccionario requeriría marcar todos " "los objetos accesibles desde allí como de solo lectura -- y nuevamente, los " "objetos autoreferenciados podrían causar un bucle infinito." #: ../Doc/faq/design.rst:498 msgid "" "There is a trick to get around this if you need to, but use it at your own " "risk: You can wrap a mutable structure inside a class instance which has " "both a :meth:`__eq__` and a :meth:`__hash__` method. You must then make " "sure that the hash value for all such wrapper objects that reside in a " "dictionary (or other hash based structure), remain fixed while the object is " "in the dictionary (or other structure). ::" msgstr "" "Hay un truco para evitar esto si lo necesita, pero úselo bajo su propio " "riesgo: puede envolver una estructura mutable dentro de una instancia de " "clase que tenga un método :meth:`__eq__` y a :meth:`__hash__` . Luego debe " "asegurarse de que el valor hash para todos los objetos de contenedor que " "residen en un diccionario (u otra estructura basada en hash) permanezca fijo " "mientras el objeto está en el diccionario (u otra estructura). ::" #: ../Doc/faq/design.rst:522 msgid "" "Note that the hash computation is complicated by the possibility that some " "members of the list may be unhashable and also by the possibility of " "arithmetic overflow." msgstr "" "Tenga en cuenta que el cálculo de hash se complica por la posibilidad de que " "algunos miembros de la lista sean inquebrantables y también por la " "posibilidad de desbordamiento aritmético." #: ../Doc/faq/design.rst:526 msgid "" "Furthermore it must always be the case that if ``o1 == o2`` (ie ``o1." "__eq__(o2) is True``) then ``hash(o1) == hash(o2)`` (ie, ``o1.__hash__() == " "o2.__hash__()``), regardless of whether the object is in a dictionary or " "not. If you fail to meet these restrictions dictionaries and other hash " "based structures will misbehave." msgstr "" "Además, siempre debe darse el caso de que si ``o1 == o2`` (es decir, ``o1." "__eq__(o2) is True``), entonces ``hash(o1) == hash(o2)`` (es decir, ``o1." "__hash__() == o2.__hash__()``), independientemente de si el objeto está en " "un diccionario o no. Si no cumple con estas restricciones, los diccionarios " "y otras estructuras basadas en hash se comportarán mal." #: ../Doc/faq/design.rst:531 msgid "" "In the case of ListWrapper, whenever the wrapper object is in a dictionary " "the wrapped list must not change to avoid anomalies. Don't do this unless " "you are prepared to think hard about the requirements and the consequences " "of not meeting them correctly. Consider yourself warned." msgstr "" "En el caso de ListWrapper, siempre que el objeto contenedor esté en un " "diccionario, la lista ajustada no debe cambiar para evitar anomalías. No " "haga esto a menos que esté preparado para pensar detenidamente sobre los " "requisitos y las consecuencias de no cumplirlos correctamente. Considérese " "advertido." #: ../Doc/faq/design.rst:538 msgid "Why doesn't list.sort() return the sorted list?" msgstr "¿Por qué list.sort() no retorna la lista ordenada?" #: ../Doc/faq/design.rst:540 msgid "" "In situations where performance matters, making a copy of the list just to " "sort it would be wasteful. Therefore, :meth:`list.sort` sorts the list in " "place. In order to remind you of that fact, it does not return the sorted " "list. This way, you won't be fooled into accidentally overwriting a list " "when you need a sorted copy but also need to keep the unsorted version " "around." msgstr "" "En situaciones donde el rendimiento es importante, hacer una copia de la " "lista solo para ordenarlo sería un desperdicio. Por lo tanto, :meth:`list." "sort` ordena la lista en su lugar. Para recordarle ese hecho, no retorna la " "lista ordenada. De esta manera, no se dejará engañar por sobreescribir " "accidentalmente una lista cuando necesite una copia ordenada, pero también " "deberá mantener la versión sin ordenar." #: ../Doc/faq/design.rst:546 msgid "" "If you want to return a new list, use the built-in :func:`sorted` function " "instead. This function creates a new list from a provided iterable, sorts " "it and returns it. For example, here's how to iterate over the keys of a " "dictionary in sorted order::" msgstr "" "Si desea retornar una nueva lista, use la función incorporada :func:`sorted` " "en su lugar. Esta función crea una nueva lista a partir de un iterativo " "proporcionado, la ordena y la retorna. Por ejemplo, a continuación se " "explica cómo iterar sobre las teclas de un diccionario en orden ordenado:" #: ../Doc/faq/design.rst:556 msgid "How do you specify and enforce an interface spec in Python?" msgstr "¿Cómo se especifica y aplica una especificación de interfaz en Python?" #: ../Doc/faq/design.rst:558 msgid "" "An interface specification for a module as provided by languages such as C++ " "and Java describes the prototypes for the methods and functions of the " "module. Many feel that compile-time enforcement of interface specifications " "helps in the construction of large programs." msgstr "" "Una especificación de interfaz para un módulo proporcionada por lenguajes " "como C++ y Java describe los prototipos para los métodos y funciones del " "módulo. Muchos sienten que la aplicación en tiempo de compilación de las " "especificaciones de la interfaz ayuda en la construcción de grandes " "programas." #: ../Doc/faq/design.rst:563 msgid "" "Python 2.6 adds an :mod:`abc` module that lets you define Abstract Base " "Classes (ABCs). You can then use :func:`isinstance` and :func:`issubclass` " "to check whether an instance or a class implements a particular ABC. The :" "mod:`collections.abc` module defines a set of useful ABCs such as :class:" "`~collections.abc.Iterable`, :class:`~collections.abc.Container`, and :class:" "`~collections.abc.MutableMapping`." msgstr "" "Python 2.6 agrega un módulo :mod:`abc` que le permite definir clases base " "abstractas (ABC). Luego puede usar :func:`isinstance` y :func:`issubclass` " "para verificar si una instancia o una clase implementa un ABC en particular. " "El módulo :mod:`collections.abc` define un conjunto de ABC útiles como :" "class:`~collections.abc.Iterable`, :class:`~collections.abc.Container` y :" "class:`~collections.abc.MutableMapping`." #: ../Doc/faq/design.rst:570 msgid "" "For Python, many of the advantages of interface specifications can be " "obtained by an appropriate test discipline for components." msgstr "" "Para Python, muchas de las ventajas de las especificaciones de interfaz se " "pueden obtener mediante una disciplina de prueba adecuada para los " "componentes." #: ../Doc/faq/design.rst:573 msgid "" "A good test suite for a module can both provide a regression test and serve " "as a module interface specification and a set of examples. Many Python " "modules can be run as a script to provide a simple \"self test.\" Even " "modules which use complex external interfaces can often be tested in " "isolation using trivial \"stub\" emulations of the external interface. The :" "mod:`doctest` and :mod:`unittest` modules or third-party test frameworks can " "be used to construct exhaustive test suites that exercise every line of code " "in a module." msgstr "" "Un buen conjunto de pruebas para un módulo puede proporcionar una prueba de " "regresión y servir como una especificación de interfaz de módulo y un " "conjunto de ejemplos. Muchos módulos de Python se pueden ejecutar como un " "script para proporcionar una simple \"autocomprobación\". Incluso los " "módulos que usan interfaces externas complejas a menudo se pueden probar de " "forma aislada utilizando emulaciones triviales de \"stub\" de la interfaz " "externa. Los módulos :mod:`doctest` y :mod:`unittest` o marcos de prueba de " "terceros se pueden utilizar para construir conjuntos de pruebas exhaustivas " "que ejercitan cada línea de código en un módulo." #: ../Doc/faq/design.rst:581 msgid "" "An appropriate testing discipline can help build large complex applications " "in Python as well as having interface specifications would. In fact, it can " "be better because an interface specification cannot test certain properties " "of a program. For example, the :meth:`append` method is expected to add new " "elements to the end of some internal list; an interface specification cannot " "test that your :meth:`append` implementation will actually do this " "correctly, but it's trivial to check this property in a test suite." msgstr "" "Una disciplina de prueba adecuada puede ayudar a construir grandes " "aplicaciones complejas en Python, así como tener especificaciones de " "interfaz. De hecho, puede ser mejor porque una especificación de interfaz no " "puede probar ciertas propiedades de un programa. Por ejemplo, se espera que " "el método :meth:`append` agregue nuevos elementos al final de alguna lista " "interna; una especificación de interfaz no puede probar que su " "implementación :meth:`append` realmente haga esto correctamente, pero es " "trivial verificar esta propiedad en un conjunto de pruebas." #: ../Doc/faq/design.rst:589 msgid "" "Writing test suites is very helpful, and you might want to design your code " "to make it easily tested. One increasingly popular technique, test-driven " "development, calls for writing parts of the test suite first, before you " "write any of the actual code. Of course Python allows you to be sloppy and " "not write test cases at all." msgstr "" "Escribir conjuntos de pruebas es muy útil, y es posible que desee diseñar su " "código con miras a que sea fácilmente probado. Una técnica cada vez más " "popular, el desarrollo dirigido por pruebas, requiere escribir partes del " "conjunto de pruebas primero, antes de escribir el código real. Por supuesto, " "Python te permite ser descuidado y no escribir casos de prueba." #: ../Doc/faq/design.rst:597 msgid "Why is there no goto?" msgstr "¿Por qué no hay goto?" #: ../Doc/faq/design.rst:599 msgid "" "In the 1970s people realized that unrestricted goto could lead to messy " "\"spaghetti\" code that was hard to understand and revise. In a high-level " "language, it is also unneeded as long as there are ways to branch (in " "Python, with ``if`` statements and ``or``, ``and``, and ``if-else`` " "expressions) and loop (with ``while`` and ``for`` statements, possibly " "containing ``continue`` and ``break``)." msgstr "" "En la década de 1970, la gente se dio cuenta de que el goto irrestricto " "podía generar un código \"espagueti\" desordenado que era difícil de " "entender y revisar. En un lenguaje de alto nivel, también es innecesario " "siempre que haya formas de bifurcar (en Python, con declaraciones ``if`` y " "expresiones ``or``, ``and`` e ``if-else``) y repetir (con declaraciones " "``while`` y ``for``, que posiblemente contengan ``continue`` y ``break``)." #: ../Doc/faq/design.rst:606 msgid "" "One can also use exceptions to provide a \"structured goto\" that works even " "across function calls. Many feel that exceptions can conveniently emulate " "all reasonable uses of the \"go\" or \"goto\" constructs of C, Fortran, and " "other languages. For example::" msgstr "" "Puede usar excepciones para proporcionar un \"goto estructurado\" que " "incluso funciona en llamadas a funciones. Muchos creen que las excepciones " "pueden emular convenientemente todos los usos razonables de los constructos " "\"go\" o \"goto\" de C, Fortran y otros lenguajes. Por ejemplo::" #: ../Doc/faq/design.rst:622 msgid "" "This doesn't allow you to jump into the middle of a loop, but that's usually " "considered an abuse of goto anyway. Use sparingly." msgstr "" "Esto no le permite saltar a la mitad de un bucle, pero de todos modos eso " "generalmente se considera un abuso de goto. Utilizar con moderación." #: ../Doc/faq/design.rst:627 msgid "Why can't raw strings (r-strings) end with a backslash?" msgstr "" "¿Por qué las cadenas de caracteres sin formato (r-strings) no pueden " "terminar con una barra diagonal inversa?" #: ../Doc/faq/design.rst:629 msgid "" "More precisely, they can't end with an odd number of backslashes: the " "unpaired backslash at the end escapes the closing quote character, leaving " "an unterminated string." msgstr "" "Más precisamente, no pueden terminar con un número impar de barras " "invertidas: la barra invertida no emparejada al final escapa el carácter de " "comillas de cierre, dejando una cadena sin terminar." #: ../Doc/faq/design.rst:633 msgid "" "Raw strings were designed to ease creating input for processors (chiefly " "regular expression engines) that want to do their own backslash escape " "processing. Such processors consider an unmatched trailing backslash to be " "an error anyway, so raw strings disallow that. In return, they allow you to " "pass on the string quote character by escaping it with a backslash. These " "rules work well when r-strings are used for their intended purpose." msgstr "" "Las cadenas de caracteres sin formato se diseñaron para facilitar la " "creación de entradas para procesadores (principalmente motores de expresión " "regular) que desean realizar su propio procesamiento de escape de barra " "invertida. Tales procesadores consideran que una barra invertida sin par es " "un error de todos modos, por lo que las cadenas de caracteres sin procesar " "no lo permiten. A cambio, le permiten pasar el carácter de comillas de " "cadena escapándolo con una barra invertida. Estas reglas funcionan bien " "cuando las cadenas de caracteres r (*r-strings*) se usan para el propósito " "previsto." #: ../Doc/faq/design.rst:640 msgid "" "If you're trying to build Windows pathnames, note that all Windows system " "calls accept forward slashes too::" msgstr "" "Si está intentando construir nombres de ruta de Windows, tenga en cuenta que " "todas las llamadas al sistema de Windows también aceptan barras diagonales:" #: ../Doc/faq/design.rst:645 msgid "" "If you're trying to build a pathname for a DOS command, try e.g. one of ::" msgstr "" "Si está tratando de construir una ruta para un comando de DOS, intente por " "ejemplo uno de los siguientes::" #: ../Doc/faq/design.rst:653 msgid "Why doesn't Python have a \"with\" statement for attribute assignments?" msgstr "" "¿Por qué Python no tiene una declaración \"with\" para las asignaciones de " "atributos?" #: ../Doc/faq/design.rst:655 msgid "" "Python has a 'with' statement that wraps the execution of a block, calling " "code on the entrance and exit from the block. Some languages have a " "construct that looks like this::" msgstr "" "Python tiene una declaración 'with' que envuelve la ejecución de un bloque, " "llamando al código en la entrada y salida del bloque. Algunos lenguajes " "tienen una construcción que se ve así:" #: ../Doc/faq/design.rst:663 msgid "In Python, such a construct would be ambiguous." msgstr "En Python, tal construcción sería ambigua." #: ../Doc/faq/design.rst:665 msgid "" "Other languages, such as Object Pascal, Delphi, and C++, use static types, " "so it's possible to know, in an unambiguous way, what member is being " "assigned to. This is the main point of static typing -- the compiler " "*always* knows the scope of every variable at compile time." msgstr "" "Otros lenguajes, como Object Pascal, Delphi y C ++, utilizan tipos " "estáticos, por lo que es posible saber, de manera inequívoca, a qué miembro " "se le está asignando. Este es el punto principal de la escritura estática: " "el compilador *siempre* conoce el alcance de cada variable en tiempo de " "compilación." #: ../Doc/faq/design.rst:670 msgid "" "Python uses dynamic types. It is impossible to know in advance which " "attribute will be referenced at runtime. Member attributes may be added or " "removed from objects on the fly. This makes it impossible to know, from a " "simple reading, what attribute is being referenced: a local one, a global " "one, or a member attribute?" msgstr "" "Python usa tipos dinámicos. Es imposible saber de antemano a qué atributo se " "hará referencia en tiempo de ejecución. Los atributos de los miembros pueden " "agregarse o eliminarse de los objetos sobre la marcha. Esto hace que sea " "imposible saber, a partir de una simple lectura, a qué atributo se hace " "referencia: ¿uno local, uno global o un atributo miembro?" #: ../Doc/faq/design.rst:676 msgid "For instance, take the following incomplete snippet::" msgstr "Por ejemplo, tome el siguiente fragmento incompleto::" #: ../Doc/faq/design.rst:682 msgid "" "The snippet assumes that \"a\" must have a member attribute called \"x\". " "However, there is nothing in Python that tells the interpreter this. What " "should happen if \"a\" is, let us say, an integer? If there is a global " "variable named \"x\", will it be used inside the with block? As you see, " "the dynamic nature of Python makes such choices much harder." msgstr "" "El fragmento supone que \"a\" debe tener un atributo miembro llamado \"x\". " "Sin embargo, no hay nada en Python que le diga esto al intérprete. ¿Qué " "debería suceder si \"a\" es, digamos, un número entero? Si hay una variable " "global llamada \"x\", ¿se usará dentro del bloque with? Como puede ver, la " "naturaleza dinámica de Python hace que tales elecciones sean mucho más " "difíciles." #: ../Doc/faq/design.rst:688 msgid "" "The primary benefit of \"with\" and similar language features (reduction of " "code volume) can, however, easily be achieved in Python by assignment. " "Instead of::" msgstr "" "Sin embargo, el beneficio principal de \"with\" y características de " "lenguaje similares (reducción del volumen del código) se puede lograr " "fácilmente en Python mediante la asignación. En vez de::" #: ../Doc/faq/design.rst:695 msgid "write this::" msgstr "escribe esto::" #: ../Doc/faq/design.rst:702 msgid "" "This also has the side-effect of increasing execution speed because name " "bindings are resolved at run-time in Python, and the second version only " "needs to perform the resolution once." msgstr "" "Esto también tiene el efecto secundario de aumentar la velocidad de " "ejecución porque los enlaces de nombres se resuelven en tiempo de ejecución " "en Python, y la segunda versión solo necesita realizar la resolución una vez." #: ../Doc/faq/design.rst:708 msgid "Why don't generators support the with statement?" msgstr "¿Por qué los generadores no admiten la declaración with?" #: ../Doc/faq/design.rst:710 msgid "" "For technical reasons, a generator used directly as a context manager would " "not work correctly. When, as is most common, a generator is used as an " "iterator run to completion, no closing is needed. When it is, wrap it as " "\"contextlib.closing(generator)\" in the 'with' statement." msgstr "" "Por razones técnicas, un generador utilizado directamente como gestor de " "contexto no funcionaría correctamente. Cuando, como es más común, un " "generador se utiliza como iterador ejecutado hasta su finalización, no es " "necesario cerrar. Cuando lo esté, envuélvalo como un\"contextlib." "closing(generator)\" en la instrucción 'with'." #: ../Doc/faq/design.rst:717 msgid "Why are colons required for the if/while/def/class statements?" msgstr "" "¿Por qué se requieren dos puntos para las declaraciones if/while/def/class?" #: ../Doc/faq/design.rst:719 msgid "" "The colon is required primarily to enhance readability (one of the results " "of the experimental ABC language). Consider this::" msgstr "" "Los dos puntos se requieren principalmente para mejorar la legibilidad (uno " "de los resultados del lenguaje ABC experimental). Considera esto::" #: ../Doc/faq/design.rst:725 msgid "versus ::" msgstr "versus ::" #: ../Doc/faq/design.rst:730 msgid "" "Notice how the second one is slightly easier to read. Notice further how a " "colon sets off the example in this FAQ answer; it's a standard usage in " "English." msgstr "" "Observe cómo el segundo es un poco más fácil de leer. Observe más a fondo " "cómo los dos puntos establecen el ejemplo en esta respuesta de preguntas " "frecuentes; Es un uso estándar en inglés." #: ../Doc/faq/design.rst:733 msgid "" "Another minor reason is that the colon makes it easier for editors with " "syntax highlighting; they can look for colons to decide when indentation " "needs to be increased instead of having to do a more elaborate parsing of " "the program text." msgstr "" "Otra razón menor es que los dos puntos facilitan a los editores con " "resaltado de sintaxis; pueden buscar dos puntos para decidir cuándo se debe " "aumentar la indentación en lugar de tener que hacer un análisis más " "elaborado del texto del programa." #: ../Doc/faq/design.rst:739 msgid "Why does Python allow commas at the end of lists and tuples?" msgstr "¿Por qué Python permite comas al final de las listas y tuplas?" #: ../Doc/faq/design.rst:741 msgid "" "Python lets you add a trailing comma at the end of lists, tuples, and " "dictionaries::" msgstr "" "Python le permite agregar una coma final al final de las listas, tuplas y " "diccionarios::" #: ../Doc/faq/design.rst:752 msgid "There are several reasons to allow this." msgstr "Hay varias razones para permitir esto." #: ../Doc/faq/design.rst:754 msgid "" "When you have a literal value for a list, tuple, or dictionary spread across " "multiple lines, it's easier to add more elements because you don't have to " "remember to add a comma to the previous line. The lines can also be " "reordered without creating a syntax error." msgstr "" "Cuando tiene un valor literal para una lista, tupla o diccionario " "distribuido en varias líneas, es más fácil agregar más elementos porque no " "tiene que recordar agregar una coma a la línea anterior. Las líneas también " "se pueden reordenar sin crear un error de sintaxis." #: ../Doc/faq/design.rst:759 msgid "" "Accidentally omitting the comma can lead to errors that are hard to " "diagnose. For example::" msgstr "" "La omisión accidental de la coma puede ocasionar errores difíciles de " "diagnosticar. Por ejemplo::" #: ../Doc/faq/design.rst:769 msgid "" "This list looks like it has four elements, but it actually contains three: " "\"fee\", \"fiefoo\" and \"fum\". Always adding the comma avoids this source " "of error." msgstr "" "Parece que esta lista tiene cuatro elementos, pero en realidad contiene " "tres: \"fee\", \"fiefoo\" y \"fum\". Agregar siempre la coma evita esta " "fuente de error." #: ../Doc/faq/design.rst:772 msgid "" "Allowing the trailing comma may also make programmatic code generation " "easier." msgstr "" "Permitir la coma final también puede facilitar la generación de código " "programático."