diff --git a/dictionaries/library_typing.txt b/dictionaries/library_typing.txt index 3ce8cbcca5..6df7bc142f 100644 --- a/dictionaries/library_typing.txt +++ b/dictionaries/library_typing.txt @@ -1,8 +1,83 @@ +Absolute +Ann +Annotated +Bucket +Combiner +Concatenate +Employee +Generic +Matrix +Movie +Never +Okay +Proto +Revealed +Starship +Tambien +Ts +Unrelated +Variadic +Vec +Yup +abs +allowed +another +asignacin +backports +bad +bound +broadcast +capitalized +cb +comprobadores +concat +concatenate +cualificador +damage +despues +employees +enterprise +exhaustividad +greet +greetings +hi +inner interdependientes +kind +manner +maxitems +maxlen +movie +mutate +my +never +numbers +overrides +predicate +prints +proper +provides +raises +reasignaciones +results +retroportaciones +reveal +revealed +scalar +second +servers +status +team +there tipificación +together +tup +two +typeddict +typo +usuarie variádico variádicos -cualificador -usuarie -exhaustividad -backports +veficiación +way +year diff --git a/library/typing.po b/library/typing.po index 37e33faa92..34275606a7 100644 --- a/library/typing.po +++ b/library/typing.po @@ -11,15 +11,16 @@ msgstr "" "Project-Id-Version: Python 3.8\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2024-11-21 16:38-0300\n" -"PO-Revision-Date: 2024-11-21 11:04-0500\n" -"Last-Translator: Alfonso Areiza Guerra \n" -"Language: es\n" +"PO-Revision-Date: 2024-11-24 14:22+0100\n" +"Last-Translator: Cristián Maureira-Fredes \n" "Language-Team: python-doc-es\n" -"Plural-Forms: nplurals=2; plural=(n != 1);\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.16.0\n" +"X-Generator: Poedit 3.4.2\n" #: ../Doc/library/typing.rst:3 msgid ":mod:`typing` --- Support for type hints" @@ -30,30 +31,32 @@ msgid "**Source code:** :source:`Lib/typing.py`" msgstr "**Source code:** :source:`Lib/typing.py`" #: ../Doc/library/typing.rst:20 -#, fuzzy msgid "" "The Python runtime does not enforce function and variable type annotations. " "They can be used by third party tools such as :term:`type checkers `, IDEs, linters, etc." msgstr "" -"En tiempo de ejecución, Python no impone las anotaciones de tipado en " -"funciones y variables. Pueden ser utilizadas por herramientas de terceros " -"como validadores de tipado, IDEs, linters, etc." +"El entorno de ejecución de Python no exige anotaciones de tipos de funciones " +"y variables. Pueden ser utilizadas por herramientas de terceros como :term:" +"`type checkers `, IDE, linters, etc." #: ../Doc/library/typing.rst:26 -#, fuzzy msgid "This module provides runtime support for type hints." -msgstr ":mod:`typing` --- Soporte para *type hints*" +msgstr "" +"Este módulo proporciona soporte en tiempo de ejecución para sugerencias de " +"tipo." #: ../Doc/library/typing.rst:28 msgid "Consider the function below::" -msgstr "" +msgstr "Considere la función a continuación::" #: ../Doc/library/typing.rst:30 msgid "" "def surface_area_of_cube(edge_length: float) -> str:\n" " return f\"The surface area of the cube is {6 * edge_length ** 2}.\"" msgstr "" +"def surface_area_of_cube(edge_length: float) -> str:\n" +" return f\"The surface area of the cube is {6 * edge_length ** 2}.\"" #: ../Doc/library/typing.rst:33 msgid "" @@ -62,6 +65,10 @@ msgid "" "``edge_length: float``. The function is expected to return an instance of :" "class:`str`, as indicated by the ``-> str`` hint." msgstr "" +"La función ``surface_area_of_cube`` toma un argumento que se espera que sea " +"una instancia de :class:`float`, como lo indica :term:`type hint` " +"``edge_length: float``. Se espera que la función devuelva una instancia de :" +"class:`str`, como lo indica la sugerencia ``-> str``." #: ../Doc/library/typing.rst:38 msgid "" @@ -69,18 +76,19 @@ msgid "" "they can also be more complex. The :mod:`typing` module provides a " "vocabulary of more advanced type hints." msgstr "" +"Si bien las sugerencias de tipos pueden ser clases simples como :class:" +"`float` o :class:`str`, también pueden ser más complejas. El módulo :mod:" +"`typing` proporciona un vocabulario de sugerencias de tipos más avanzadas." #: ../Doc/library/typing.rst:42 -#, fuzzy msgid "" "New features are frequently added to the ``typing`` module. The :pypi:" "`typing_extensions` package provides backports of these new features to " "older versions of Python." msgstr "" -"Frecuentemente se agregan nuevas funcionalidades al módulo ``typing``. El " -"paquete `typing_extensions `_ " -"provee backports de estas nuevas funcionalidades para versiones más antiguas " -"de Python." +"Con frecuencia se agregan nuevas funciones al módulo ``typing``. El paquete :" +"pypi:`typing_extensions` proporciona versiones anteriores de estas nuevas " +"funciones para versiones anteriores de Python." #: ../Doc/library/typing.rst:49 msgid "" @@ -131,7 +139,7 @@ msgstr "" #: ../Doc/library/typing.rst:64 msgid "Specification for the Python Type System" -msgstr "" +msgstr "Especificación del sistema de tipos de Python" #: ../Doc/library/typing.rst:66 msgid "" @@ -139,6 +147,9 @@ msgid "" "found at `\"Specification for the Python type system\" `_." msgstr "" +"La especificación canónica y actualizada del sistema de tipos Python se " +"puede encontrar en `\"Specification for the Python type system\" `_." #: ../Doc/library/typing.rst:72 msgid "Type aliases" @@ -165,6 +176,13 @@ msgid "" "# passes type checking; a list of floats qualifies as a Vector.\n" "new_vector = scale(2.0, [1.0, -4.2, 5.4])" msgstr "" +"type Vector = list[float]\n" +"\n" +"def scale(scalar: float, vector: Vector) -> Vector:\n" +" return [scalar * num for num in vector]\n" +"\n" +"# pasa las verificaciones de tipo; una lista de float califica como Vector.\n" +"new_vector = scale(2.0, [1.0, -4.2, 5.4])" #: ../Doc/library/typing.rst:87 msgid "" @@ -205,7 +223,7 @@ msgstr "" #: ../Doc/library/typing.rst:109 msgid "Vector = list[float]" -msgstr "" +msgstr "Vector = list[float]" #: ../Doc/library/typing.rst:111 msgid "" @@ -221,6 +239,9 @@ msgid "" "\n" "Vector: TypeAlias = list[float]" msgstr "" +"from typing import TypeAlias\n" +"\n" +"Vector: TypeAlias = list[float]" #: ../Doc/library/typing.rst:121 msgid "NewType" @@ -237,6 +258,10 @@ msgid "" "UserId = NewType('UserId', int)\n" "some_id = UserId(524313)" msgstr "" +"from typing import NewType\n" +"\n" +"UserId = NewType('UserId', int)\n" +"some_id = UserId(524313)" #: ../Doc/library/typing.rst:130 msgid "" @@ -257,6 +282,14 @@ msgid "" "# fails type checking; an int is not a UserId\n" "user_b = get_user_name(-1)" msgstr "" +"def get_user_name(user_id: UserId) -> str:\n" +" ...\n" +"\n" +"# pasa la verificación de tipos\n" +"user_a = get_user_name(UserId(42351))\n" +"\n" +"# falla la verificación de tipos; un int no es un UserId\n" +"user_b = get_user_name(-1)" #: ../Doc/library/typing.rst:142 msgid "" @@ -275,6 +308,8 @@ msgid "" "# 'output' is of type 'int', not 'UserId'\n" "output = UserId(23413) + UserId(54341)" msgstr "" +"# 'output' es del tipo 'int', no 'UserId'\n" +"output = UserId(23413) + UserId(54341)" #: ../Doc/library/typing.rst:150 msgid "" @@ -312,6 +347,12 @@ msgid "" "# Fails at runtime and does not pass type checking\n" "class AdminUserId(UserId): pass" msgstr "" +"from typing import NewType\n" +"\n" +"UserId = NewType('UserId', int)\n" +"\n" +"# Falla en runtime y no pasa la verificación de tipos\n" +"class AdminUserId(UserId): pass" #: ../Doc/library/typing.rst:168 msgid "" @@ -329,6 +370,11 @@ msgid "" "\n" "ProUserId = NewType('ProUserId', UserId)" msgstr "" +"from typing import NewType\n" +"\n" +"UserId = NewType('UserId', int)\n" +"\n" +"ProUserId = NewType('ProUserId', UserId)" #: ../Doc/library/typing.rst:176 msgid "and typechecking for ``ProUserId`` will work as expected." @@ -391,17 +437,16 @@ msgid "Annotating callable objects" msgstr "Anotaciones en objetos invocables" #: ../Doc/library/typing.rst:210 -#, fuzzy msgid "" "Functions -- or other :term:`callable` objects -- can be annotated using :" "class:`collections.abc.Callable` or deprecated :data:`typing.Callable`. " "``Callable[[int], str]`` signifies a function that takes a single parameter " "of type :class:`int` and returns a :class:`str`." msgstr "" -"Las funciones -- u otro objeto invocable :term:`callable` se pueden anotar " -"utilizando :class:`collections.abc.Callable` o :data:`typing.Callable`. " -"``Callable[[int], str]`` se refiere a una función que toma un solo parámetro " -"de tipo :class:`int` y retorna un :class:`str`." +"Las funciones (u otros objetos :term:`callable`) se pueden anotar " +"utilizando :class:`collections.abc.Callable` o el obsoleto :data:`typing." +"Callable`. ``Callable[[int], str]`` significa una función que toma un único " +"parámetro de tipo :class:`int` y devuelve un :class:`str`." #: ../Doc/library/typing.rst:215 ../Doc/library/typing.rst:3128 #: ../Doc/library/typing.rst:3308 @@ -424,6 +469,19 @@ msgid "" "\n" "callback: Callable[[str], Awaitable[None]] = on_update" msgstr "" +"from collections.abc import Callable, Awaitable\n" +"\n" +"def feeder(get_next_item: Callable[[], str]) -> None:\n" +" ... # Body\n" +"\n" +"def async_query(on_success: Callable[[int], None],\n" +" on_error: Callable[[int, Exception], None]) -> None:\n" +" ... # Body\n" +"\n" +"async def on_update(value: str) -> None:\n" +" ... # Body\n" +"\n" +"callback: Callable[[str], Awaitable[None]] = on_update" #: ../Doc/library/typing.rst:233 msgid "" @@ -454,9 +512,14 @@ msgid "" "x = str # OK\n" "x = concat # Also OK" msgstr "" +"def concat(x: str, y: str) -> str:\n" +" return x + y\n" +"\n" +"x: Callable[..., str]\n" +"x = str # OK\n" +"x = concat # Also OK" #: ../Doc/library/typing.rst:250 -#, fuzzy msgid "" "``Callable`` cannot express complex signatures such as functions that take a " "variadic number of arguments, :ref:`overloaded functions `, or " @@ -464,11 +527,11 @@ msgid "" "be expressed by defining a :class:`Protocol` class with a :meth:`~object." "__call__` method:" msgstr "" -"``Callable`` no puede representar firmas complejas como funciones que toman " -"un número variado de argumentos, :func:`funciones sobrecargadas ` " -"o funciones que reciben parámetros de solo palabras clave. Sin embargo, " -"estas firmas se pueden definir al definir una clase :class:`Protocol` con un " -"método :meth:`~object.__call__` method:" +"``Callable`` no puede expresar firmas complejas, como funciones que toman un " +"número variádico de argumentos, :ref:`overloaded functions ` o " +"funciones que tienen parámetros que solo contienen palabras clave. Sin " +"embargo, estas firmas se pueden expresar definiendo una clase :class:" +"`Protocol` con un método :meth:`~object.__call__`:" #: ../Doc/library/typing.rst:256 msgid "" @@ -573,6 +636,11 @@ msgid "" "\"T\"\n" " return l[0]" msgstr "" +"from collections.abc import Sequence\n" +"\n" +"def first[T](l: Sequence[T]) -> T: # La función es genérica sobre el " +"TypeVar \"T\"\n" +" return l[0]" #: ../Doc/library/typing.rst:323 msgid "Or by using the :class:`TypeVar` factory directly::" @@ -589,6 +657,14 @@ msgid "" "\"U\"\n" " return l[1]" msgstr "" +"from collections.abc import Sequence\n" +"from typing import TypeVar\n" +"\n" +"U = TypeVar('U') # Declara variable tipo \"U\"\n" +"\n" +"def second(l: Sequence[U]) -> U: # La función es genérica sobre TypeVar " +"\"U\"\n" +" return l[1]" #: ../Doc/library/typing.rst:333 msgid "Syntactic support for generics is new in Python 3.12." @@ -620,6 +696,20 @@ msgid "" "# and that all values in ``z`` are meant to be either strings or ints\n" "z: Mapping[str, str | int] = {}" msgstr "" +"from collections.abc import Mapping\n" +"\n" +"# El verificador de tipos inferirá que todos los elementos en ``x`` deben " +"ser ints\n" +"x: list[int] = []\n" +"\n" +"#Error del verificador de tipo: ``list`` solo acepta un único argumento de " +"tipo:\n" +"y: list[int, str] = [1, 'foo']\n" +"\n" +"# El verificador de tipos inferirá que todas las claves en ``z`` deben ser " +"strings,\n" +"# y que todos los valores en ``z`` deben ser strings o ints\n" +"z: Mapping[str, str | int] = {}" #: ../Doc/library/typing.rst:356 msgid "" @@ -661,6 +751,17 @@ msgid "" "# but ``z`` has been assigned to a tuple of length 3\n" "z: tuple[int] = (1, 2, 3)" msgstr "" +"# OK: ``x`` se asigna a una tupla de longitud 1 donde el único elemento es " +"un int\n" +"x: tuple[int] = (5,)\n" +"\n" +"# OK: ``y`` se asigna a una tupla de longitud 2;\n" +"# el elemento 1 es un int, el elemento 2 es una cadena\n" +"y: tuple[int, str] = (5, \"foo\")\n" +"\n" +"# Error: la anotación de tipo indica una tupla de longitud 1,\n" +"# pero ``z`` se ha asignado a una tupla de longitud 3\n" +"z: tuple[int] = (1, 2, 3)" #: ../Doc/library/typing.rst:378 msgid "" @@ -699,7 +800,6 @@ msgid "The type of class objects" msgstr "El tipo de objetos de clase" #: ../Doc/library/typing.rst:403 -#, fuzzy msgid "" "A variable annotated with ``C`` may accept a value of type ``C``. In " "contrast, a variable annotated with ``type[C]`` (or deprecated :class:" @@ -708,8 +808,8 @@ msgid "" msgstr "" "Una variable anotada con ``C`` puede aceptar un valor de tipo ``C``. Por el " "contrario, una variable anotada con ``type[C]`` (o :class:`typing.Type[C] " -"`) puede aceptar valores que sean clases en sí mismas; " -"específicamente, aceptará el *objeto de clase* de ``C``. Por ejemplo:" +"` en desuso) puede aceptar valores que sean clases en sí mismos; " +"específicamente, aceptará el *class object* de ``C``. Por ejemplo:" #: ../Doc/library/typing.rst:409 msgid "" @@ -717,6 +817,9 @@ msgid "" "b = int # Has type ``type[int]``\n" "c = type(a) # Also has type ``type[int]``" msgstr "" +"a = 3 # Tiene tipo ``int``\n" +"b = int # Tiene tipo ``type[int]``\n" +"c = type(a) # Tambien tiene tipo ``type[int]``" #: ../Doc/library/typing.rst:413 msgid "Note that ``type[C]`` is covariant::" @@ -740,6 +843,22 @@ msgid "" "make_new_user(int) # Error: ``type[int]`` is not a subtype of " "``type[User]``" msgstr "" +"class User: ...\n" +"class ProUser(User): ...\n" +"class TeamUser(User): ...\n" +"\n" +"def make_new_user(user_class: type[User]) -> User:\n" +" # ...\n" +" return user_class()\n" +"\n" +"make_new_user(User) # OK\n" +"make_new_user(ProUser) # También OK: ``type[ProUser]`` es un subtipo de " +"``type[User]``\n" +"make_new_user(TeamUser) # aún está bien\n" +"make_new_user(User()) # Error: se espera ``type[User]`` pero se usó " +"``User``\n" +"make_new_user(int) # Error: ``type[int]`` no es un subtipo de " +"``type[User]``" #: ../Doc/library/typing.rst:429 msgid "" @@ -771,17 +890,17 @@ msgstr "" #: ../Doc/library/typing.rst:448 msgid "Annotating generators and coroutines" -msgstr "" +msgstr "Anotación de generadores y corrutinas" #: ../Doc/library/typing.rst:450 -#, fuzzy msgid "" "A generator can be annotated using the generic type :class:" "`Generator[YieldType, SendType, ReturnType] `. " "For example::" msgstr "" -"Un generador puede ser anotado con el tipo genérico ``Generator[YieldType, " -"SendType, ReturnType]``. Por ejemplo::" +"Se puede anotar un generador utilizando el tipo genérico :class:" +"`Generator[YieldType, SendType, ReturnType] `. " +"Por ejemplo:" #: ../Doc/library/typing.rst:454 msgid "" @@ -791,22 +910,28 @@ msgid "" " sent = yield round(sent)\n" " return 'Done'" msgstr "" +"def echo_round() -> Generator[int, float, str]:\n" +" sent = yield 0\n" +" while sent >= 0:\n" +" sent = yield round(sent)\n" +" return 'Done'" #: ../Doc/library/typing.rst:460 -#, fuzzy msgid "" "Note that unlike many other generic classes in the standard library, the " "``SendType`` of :class:`~collections.abc.Generator` behaves contravariantly, " "not covariantly or invariantly." msgstr "" -"Nótese que en contraste con muchos otros genéricos en el módulo *typing*, el " -"``SendType`` de :class:`Generator` se comporta como contravariante, no " -"covariante ni invariante." +"Tenga en cuenta que, a diferencia de muchas otras clases genéricas en la " +"biblioteca estándar, ``SendType`` de :class:`~collections.abc.Generator` se " +"comporta de manera contravariante, no covariante o invariante." #: ../Doc/library/typing.rst:464 msgid "" "The ``SendType`` and ``ReturnType`` parameters default to :const:`!None`::" msgstr "" +"Los parámetros ``SendType`` y ``ReturnType`` tienen como valor " +"predeterminado :const:`!None`::" #: ../Doc/library/typing.rst:466 msgid "" @@ -815,10 +940,14 @@ msgid "" " yield start\n" " start += 1" msgstr "" +"def infinite_stream(start: int) -> Generator[int]:\n" +" while True:\n" +" yield start\n" +" start += 1" #: ../Doc/library/typing.rst:471 msgid "It is also possible to set these types explicitly::" -msgstr "" +msgstr "También es posible configurar estos tipos explícitamente:" #: ../Doc/library/typing.rst:473 msgid "" @@ -827,6 +956,10 @@ msgid "" " yield start\n" " start += 1" msgstr "" +"def infinite_stream(start: int) -> Generator[int, None, None]:\n" +" while True:\n" +" yield start\n" +" start += 1" #: ../Doc/library/typing.rst:478 msgid "" @@ -834,6 +967,10 @@ msgid "" "having a return type of either :class:`Iterable[YieldType] ` or :class:`Iterator[YieldType] `::" msgstr "" +"Los generadores simples que solo producen valores también se pueden anotar " +"como que tienen un tipo de retorno de :class:`Iterable[YieldType] " +"` o :class:`Iterator[YieldType] `::" #: ../Doc/library/typing.rst:483 msgid "" @@ -842,6 +979,10 @@ msgid "" " yield start\n" " start += 1" msgstr "" +"def infinite_stream(start: int) -> Iterator[int]:\n" +" while True:\n" +" yield start\n" +" start += 1" #: ../Doc/library/typing.rst:488 msgid "" @@ -850,6 +991,11 @@ msgid "" "`). The ``SendType`` argument defaults to :" "const:`!None`, so the following definitions are equivalent::" msgstr "" +"Los generadores asincrónicos se manejan de manera similar, pero no espere un " +"argumento de tipo ``ReturnType`` (:class:`AsyncGenerator[YieldType, " +"SendType] `). El argumento ``SendType`` " +"tiene como valor predeterminado :const:`!None`, por lo que las siguientes " +"definiciones son equivalentes:" #: ../Doc/library/typing.rst:494 msgid "" @@ -863,6 +1009,15 @@ msgid "" " yield start\n" " start = await increment(start)" msgstr "" +"async def infinite_stream(start: int) -> AsyncGenerator[int]:\n" +" while True:\n" +" yield start\n" +" start = await increment(start)\n" +"\n" +"async def infinite_stream(start: int) -> AsyncGenerator[int, None]:\n" +" while True:\n" +" yield start\n" +" start = await increment(start)" #: ../Doc/library/typing.rst:504 msgid "" @@ -870,6 +1025,9 @@ msgid "" "abc.AsyncIterable>` and :class:`AsyncIterator[YieldType] ` are available as well::" msgstr "" +"Al igual que en el caso sincrónico, también están disponibles :class:" +"`AsyncIterable[YieldType] ` y :class:" +"`AsyncIterator[YieldType] `:" #: ../Doc/library/typing.rst:509 msgid "" @@ -878,6 +1036,10 @@ msgid "" " yield start\n" " start = await increment(start)" msgstr "" +"async def infinite_stream(start: int) -> AsyncIterator[int]:\n" +" while True:\n" +" yield start\n" +" start = await increment(start)" #: ../Doc/library/typing.rst:514 msgid "" @@ -885,6 +1047,9 @@ msgid "" "ReturnType] `. Generic arguments correspond to " "those of :class:`~collections.abc.Generator`, for example::" msgstr "" +"Las corrutinas se pueden anotar utilizando :class:`Coroutine[YieldType, " +"SendType, ReturnType] `. Los argumentos genéricos " +"corresponden a los de :class:`~collections.abc.Generator`, por ejemplo:" #: ../Doc/library/typing.rst:519 msgid "" @@ -926,17 +1091,34 @@ msgid "" " def log(self, message: str) -> None:\n" " self.logger.info('%s: %s', self.name, message)" msgstr "" +"from logging import Logger\n" +"\n" +"class LoggedVar[T]:\n" +" def __init__(self, value: T, name: str, logger: Logger) -> None:\n" +" self.name = name\n" +" self.logger = logger\n" +" self.value = value\n" +"\n" +" def set(self, new: T) -> None:\n" +" self.log('Set ' + repr(self.value))\n" +" self.value = new\n" +"\n" +" def get(self) -> T:\n" +" self.log('Get ' + repr(self.value))\n" +" return self.value\n" +"\n" +" def log(self, message: str) -> None:\n" +" self.logger.info('%s: %s', self.name, message)" #: ../Doc/library/typing.rst:553 -#, fuzzy msgid "" "This syntax indicates that the class ``LoggedVar`` is parameterised around a " "single :ref:`type variable ` ``T`` . This also makes ``T`` valid as " "a type within the class body." msgstr "" "Esta sintaxis indica que la clase ``LoggedVar`` está parametrizada en torno " -"a una única variable de tipo :class:`` ``T`` . Esto también hace " -"que ``T`` sea válida como tipo dentro del cuerpo de la clase." +"a un único :ref:`type variable ` ``T`` . Esto también hace que " +"``T`` sea válido como tipo dentro del cuerpo de la clase." #: ../Doc/library/typing.rst:557 msgid "" @@ -957,6 +1139,12 @@ msgid "" "class LoggedVar(Generic[T]):\n" " ..." msgstr "" +"from typing import TypeVar, Generic\n" +"\n" +"T = TypeVar('T')\n" +"\n" +"class LoggedVar(Generic[T]):\n" +" ..." #: ../Doc/library/typing.rst:568 msgid "" @@ -975,6 +1163,11 @@ msgid "" " for var in vars:\n" " var.set(0)" msgstr "" +"from collections.abc import Iterable\n" +"\n" +"def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n" +" for var in vars:\n" +" var.set(0)" #: ../Doc/library/typing.rst:577 msgid "" @@ -999,6 +1192,17 @@ msgid "" "class OldWeirdTrio(Generic[OldT, OldB, OldS]):\n" " ..." msgstr "" +"from typing import TypeVar, Generic, Sequence\n" +"\n" +"class WeirdTrio[T, B: Sequence[bytes], S: (int, str)]:\n" +" ...\n" +"\n" +"OldT = TypeVar('OldT', contravariant=True)\n" +"OldB = TypeVar('OldB', bound=Sequence[bytes], covariant=True)\n" +"OldS = TypeVar('OldS', int, str)\n" +"\n" +"class OldWeirdTrio(Generic[OldT, OldB, OldS]):\n" +" ..." #: ../Doc/library/typing.rst:592 msgid "" @@ -1021,6 +1225,16 @@ msgid "" "class Pair(Generic[T, T]): # INVALID\n" " ..." msgstr "" +"from typing import TypeVar, Generic\n" +"...\n" +"\n" +"class Pair[M, M]: # SyntaxError\n" +" ...\n" +"\n" +"T = TypeVar('T')\n" +"\n" +"class Pair(Generic[T, T]): # INVALID\n" +" ..." #: ../Doc/library/typing.rst:606 msgid "Generic classes can also inherit from other classes::" @@ -1033,6 +1247,10 @@ msgid "" "class LinkedList[T](Sized):\n" " ..." msgstr "" +"from collections.abc import Sized\n" +"\n" +"class LinkedList[T](Sized):\n" +" ..." #: ../Doc/library/typing.rst:613 msgid "" @@ -1047,6 +1265,10 @@ msgid "" "class MyDict[T](Mapping[str, T]):\n" " ..." msgstr "" +"from collections.abc import Mapping\n" +"\n" +"class MyDict[T](Mapping[str, T]):\n" +" ..." #: ../Doc/library/typing.rst:620 msgid "In this case ``MyDict`` has a single parameter, ``T``." @@ -1069,6 +1291,10 @@ msgid "" "class MyIterable(Iterable): # Same as Iterable[Any]\n" " ..." msgstr "" +"from collections.abc import Iterable\n" +"\n" +"class MyIterable(Iterable): # Igual que Iterable[Any]\n" +" ..." #: ../Doc/library/typing.rst:633 msgid "User-defined generic type aliases are also supported. Examples::" @@ -1092,6 +1318,19 @@ msgid "" "Iterable[tuple[T, T]]\n" " return sum(x*y for x, y in v)" msgstr "" +"from collections.abc import Iterable\n" +"\n" +"type Response[S] = Iterable[S] | int\n" +"\n" +"# Return type here is same as Iterable[str] | int\n" +"def response(query: str) -> Response[str]:\n" +" ...\n" +"\n" +"type Vec[T] = Iterable[tuple[T, T]]\n" +"\n" +"def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Same as " +"Iterable[tuple[T, T]]\n" +" return sum(x*y for x, y in v)" #: ../Doc/library/typing.rst:648 msgid "" @@ -1109,6 +1348,11 @@ msgid "" "S = TypeVar(\"S\")\n" "Response = Iterable[S] | int" msgstr "" +"from collections.abc import Iterable\n" +"from typing import TypeVar\n" +"\n" +"S = TypeVar(\"S\")\n" +"Response = Iterable[S] | int" #: ../Doc/library/typing.rst:657 msgid ":class:`Generic` no longer has a custom metaclass." @@ -1148,6 +1392,10 @@ msgid "" ">>> Z[int, [dict, float]]\n" "__main__.Z[int, [dict, float]]" msgstr "" +">>> class Z[T, **P]: ... # T es un TypeVar; P es un ParamSpec\n" +"...\n" +">>> Z[int, [dict, float]]\n" +"__main__.Z[int, [dict, float]]" #: ../Doc/library/typing.rst:676 msgid "" @@ -1166,6 +1414,12 @@ msgid "" "class Z(Generic[P]):\n" " ..." msgstr "" +"from typing import ParamSpec, Generic\n" +"\n" +"P = ParamSpec('P')\n" +"\n" +"class Z(Generic[P]):\n" +" ..." #: ../Doc/library/typing.rst:686 msgid "" @@ -1190,6 +1444,12 @@ msgid "" ">>> X[[int, str]]\n" "__main__.X[[int, str]]" msgstr "" +">>> class X[**P]: ...\n" +"...\n" +">>> X[int, str]\n" +"__main__.X[[int, str]]\n" +">>> X[[int, str]]\n" +"__main__.X[[int, str]]" #: ../Doc/library/typing.rst:699 msgid "" @@ -1262,6 +1522,20 @@ msgid "" " item.bar()\n" " ..." msgstr "" +"from typing import Any\n" +"\n" +"a: Any = None\n" +"a = [] # OK\n" +"a = 2 # OK\n" +"\n" +"s: str = ''\n" +"s = a # OK\n" +"\n" +"def foo(item: Any) -> int:\n" +" # Pasa la verificación de tipos; 'item' puede ser de cualquier tipo,\n" +" # y ese tipo puede tener el método 'bar'\n" +" item.bar()\n" +" ..." #: ../Doc/library/typing.rst:738 msgid "" @@ -1350,6 +1624,26 @@ msgid "" "hash_b(42)\n" "hash_b(\"foo\")" msgstr "" +"def hash_a(item: object) -> int:\n" +" # No pasa la comprobación de tipos; un objeto no tiene un método " +"\"mágico\".\n" +" item.magic()\n" +" ...\n" +"\n" +"def hash_b(item: Any) -> int:\n" +" # Pasa la veficiación de tipos\n" +" item.magic()\n" +" ...\n" +"\n" +"# Pasa la verificación de tipo, ya que los ints y str son subclases de " +"objeto\n" +"hash_a(42)\n" +"hash_a(\"foo\")\n" +"\n" +"# Pasa la verificación de tipo, ya que Any es compatible con todos los " +"tipos\n" +"hash_b(42)\n" +"hash_b(\"foo\")" #: ../Doc/library/typing.rst:787 msgid "" @@ -1400,6 +1694,12 @@ msgid "" " def __len__(self) -> int: ...\n" " def __iter__(self) -> Iterator[int]: ..." msgstr "" +"from collections.abc import Sized, Iterable, Iterator\n" +"\n" +"class Bucket(Sized, Iterable[int]):\n" +" ...\n" +" def __len__(self) -> int: ...\n" +" def __iter__(self) -> Iterator[int]: ..." #: ../Doc/library/typing.rst:811 msgid "" @@ -1427,6 +1727,15 @@ msgid "" "def collect(items: Iterable[int]) -> int: ...\n" "result = collect(Bucket()) # Passes type check" msgstr "" +"from collections.abc import Iterator, Iterable\n" +"\n" +"class Bucket: # Nota: sin clases base\n" +" ...\n" +" def __len__(self) -> int: ...\n" +" def __iter__(self) -> Iterator[int]: ...\n" +"\n" +"def collect(items: Iterable[int]) -> int: ...\n" +"result = collect(Bucket()) # Pasa la verificación de tipos" #: ../Doc/library/typing.rst:827 msgid "" @@ -1498,7 +1807,7 @@ msgstr "Definición::" #: ../Doc/library/typing.rst:863 msgid "AnyStr = TypeVar('AnyStr', str, bytes)" -msgstr "" +msgstr "AnyStr = TypeVar('AnyStr', str, bytes)" #: ../Doc/library/typing.rst:865 msgid "" @@ -1526,6 +1835,12 @@ msgid "" "concat(b\"foo\", b\"bar\") # OK, output has type 'bytes'\n" "concat(\"foo\", b\"bar\") # Error, cannot mix str and bytes" msgstr "" +"def concat(a: AnyStr, b: AnyStr) -> AnyStr:\n" +" return a + b\n" +"\n" +"concat(\"foo\", \"bar\") # OK, output tiene tipo 'str'\n" +"concat(b\"foo\", b\"bar\") # OK, output tiene tipo 'bytes'\n" +"concat(\"foo\", b\"bar\") # Error, no se puede mezclar str y bytes" #: ../Doc/library/typing.rst:877 msgid "" @@ -1557,6 +1872,9 @@ msgid "" "Use ``class A[T: (str, bytes)]: ...`` instead of importing ``AnyStr``. See :" "pep:`695` for more details." msgstr "" +"Obsoleto en favor del nuevo :ref:`type parameter syntax `. " +"Utilice ``class A[T: (str, bytes)]: ...`` en lugar de importar ``AnyStr``. " +"Consulte :pep:`695` para obtener más detalles." #: ../Doc/library/typing.rst:897 msgid "" @@ -1565,6 +1883,10 @@ msgid "" "imported from ``typing``. ``AnyStr`` will be removed from ``typing`` in " "Python 3.18." msgstr "" +"En Python 3.16, ``AnyStr`` se eliminará de ``typing.__all__`` y se emitirán " +"advertencias de desuso en tiempo de ejecución cuando se acceda a él o se " +"importe desde ``typing``. ``AnyStr`` se eliminará de ``typing`` en Python " +"3.18." #: ../Doc/library/typing.rst:904 msgid "Special type that includes only literal strings." @@ -1601,6 +1923,17 @@ msgid "" " f\"SELECT * FROM students WHERE name = {arbitrary_string}\"\n" " )" msgstr "" +"def run_query(sql: LiteralString) -> None:\n" +" ...\n" +"\n" +"def caller(arbitrary_string: str, literal_string: LiteralString) -> None:\n" +" run_query(\"SELECT * FROM students\") # OK\n" +" run_query(literal_string) # OK\n" +" run_query(\"SELECT * FROM \" + literal_string) # OK\n" +" run_query(arbitrary_string) # type checker error\n" +" run_query( # type checker error\n" +" f\"SELECT * FROM students WHERE name = {arbitrary_string}\"\n" +" )" #: ../Doc/library/typing.rst:928 msgid "" @@ -1620,22 +1953,20 @@ msgstr "Véase :pep:`675` para más detalle." # bottom type? #: ../Doc/library/typing.rst:940 -#, fuzzy msgid "" ":data:`!Never` and :data:`!NoReturn` represent the `bottom type `_, a type that has no members." msgstr "" -"El `bottom type `_ (tipo vacío), " -"es un tipo que no tiene miembros." +":data:`!Never` y :data:`!NoReturn` representan `bottom type `_, un tipo que no tiene miembros." -# se añade valor para matizar que la funcion retorna (retorna el control) pero -# no de manera normal. En el ejemplo lanza una excepción. #: ../Doc/library/typing.rst:944 -#, fuzzy msgid "" "They can be used to indicate that a function never returns, such as :func:" "`sys.exit`::" -msgstr "Tipo especial que indica que una función nunca retorna un valor." +msgstr "" +"Se pueden utilizar para indicar que una función nunca retorna, como :func:" +"`sys.exit`::" #: ../Doc/library/typing.rst:947 msgid "" @@ -1644,15 +1975,18 @@ msgid "" "def stop() -> Never:\n" " raise RuntimeError('no way')" msgstr "" +"from typing import Never # o NoReturn\n" +"\n" +"def stop() -> Never:\n" +" raise RuntimeError('no way')" #: ../Doc/library/typing.rst:952 -#, fuzzy msgid "" "Or to define a function that should never be called, as there are no valid " "arguments, such as :func:`assert_never`::" msgstr "" -"Puede ser utilizado para definir una función que nunca debe ser llamada, o " -"una función que nunca retorna::" +"O definir una función que nunca debe llamarse, ya que no hay argumentos " +"válidos, como :func:`assert_never`::" #: ../Doc/library/typing.rst:956 msgid "" @@ -1677,14 +2011,17 @@ msgid "" ":data:`!Never` and :data:`!NoReturn` have the same meaning in the type " "system and static type checkers treat both equivalently." msgstr "" +":data:`!Never` y :data:`!NoReturn` tienen el mismo significado en el sistema " +"de tipos y los verificadores de tipos estáticos los tratan a ambos de manera " +"equivalente." #: ../Doc/library/typing.rst:976 msgid "Added :data:`NoReturn`." -msgstr "" +msgstr "Se agregó :data:`NoReturn`." #: ../Doc/library/typing.rst:980 msgid "Added :data:`Never`." -msgstr "" +msgstr "Se agregó :data:`Never`." # ¿cómo se le llama en español a una variable "capturada" en una clausura? #: ../Doc/library/typing.rst:984 @@ -1706,6 +2043,18 @@ msgid "" "reveal_type(SubclassOfFoo().return_self()) # Revealed type is " "\"SubclassOfFoo\"" msgstr "" +"from typing import Self, reveal_type\n" +"\n" +"class Foo:\n" +" def return_self(self) -> Self:\n" +" ...\n" +" return self\n" +"\n" +"class SubclassOfFoo(Foo): pass\n" +"\n" +"reveal_type(Foo().return_self()) # Revealed type is \"Foo\"\n" +"reveal_type(SubclassOfFoo().return_self()) # Tipo revelado es " +"\"SubclassOfFoo\"" #: ../Doc/library/typing.rst:1000 msgid "" @@ -1726,6 +2075,14 @@ msgid "" " ...\n" " return self" msgstr "" +"from typing import TypeVar\n" +"\n" +"Self = TypeVar(\"Self\", bound=\"Foo\")\n" +"\n" +"class Foo:\n" +" def return_self(self: Self) -> Self:\n" +" ...\n" +" return self" #: ../Doc/library/typing.rst:1012 msgid "" @@ -1775,6 +2132,12 @@ msgid "" " def returns_eggs(self) -> \"Eggs\":\n" " return Eggs()" msgstr "" +"class Eggs:\n" +" # Self would be an incorrect return annotation here,\n" +" # as the object returned is always an instance of Eggs,\n" +" # even in subclasses\n" +" def returns_eggs(self) -> \"Eggs\":\n" +" return Eggs()" #: ../Doc/library/typing.rst:1035 msgid "See :pep:`673` for more details." @@ -1794,6 +2157,9 @@ msgid "" "\n" "Factors: TypeAlias = list[int]" msgstr "" +"from typing import TypeAlias\n" +"\n" +"Factors: TypeAlias = list[int]" #: ../Doc/library/typing.rst:1049 msgid "" @@ -1823,6 +2189,21 @@ msgid "" " @classmethod\n" " def make_box_of_strings(cls) -> BoxOfStrings: ..." msgstr "" +"from typing import Generic, TypeAlias, TypeVar\n" +"\n" +"T = TypeVar(\"T\")\n" +"\n" +"# \"Box\" aún no existe,\n" +"# entonces tenemos que usar comillas para la referencia adelantada en Python " +"<3.12.\n" +"# Usando ``TypeAlias`` le dice al verificador de tipos que es una " +"declaración de tipo alias,\n" +"# no una asignacin de variable a un string.\n" +"BoxOfStrings: TypeAlias = \"Box[str]\"\n" +"\n" +"class Box(Generic[T]):\n" +" @classmethod\n" +" def make_box_of_strings(cls) -> BoxOfStrings: ..." #: ../Doc/library/typing.rst:1069 msgid "See :pep:`613` for more details." @@ -1884,7 +2265,7 @@ msgstr "Las uniones de uniones se simplifican (se aplanan), p. ej.::" #: ../Doc/library/typing.rst:1099 msgid "Union[Union[int, str], float] == Union[int, str, float]" -msgstr "" +msgstr "Union[Union[int, str], float] == Union[int, str, float]" #: ../Doc/library/typing.rst:1101 msgid "Unions of a single argument vanish, e.g.::" @@ -1892,7 +2273,7 @@ msgstr "Las uniones con un solo argumento se eliminan, p. ej.::" #: ../Doc/library/typing.rst:1103 msgid "Union[int] == int # The constructor actually returns int" -msgstr "" +msgstr "Union[int] == int # El constructor de hecho retorna int" #: ../Doc/library/typing.rst:1105 msgid "Redundant arguments are skipped, e.g.::" @@ -1900,7 +2281,7 @@ msgstr "Argumentos repetidos se omiten, p. ej.::" #: ../Doc/library/typing.rst:1107 msgid "Union[int, str, int] == Union[int, str] == int | str" -msgstr "" +msgstr "Union[int, str, int] == Union[int, str] == int | str" #: ../Doc/library/typing.rst:1109 msgid "When comparing unions, the argument order is ignored, e.g.::" @@ -1909,7 +2290,7 @@ msgstr "" #: ../Doc/library/typing.rst:1111 msgid "Union[int, str] == Union[str, int]" -msgstr "" +msgstr "Union[int, str] == Union[str, int]" #: ../Doc/library/typing.rst:1113 msgid "You cannot subclass or instantiate a ``Union``." @@ -1952,6 +2333,8 @@ msgid "" "def foo(arg: int = 0) -> None:\n" " ..." msgstr "" +"def foo(arg: int = 0) -> None:\n" +" ..." #: ../Doc/library/typing.rst:1136 msgid "" @@ -1967,6 +2350,8 @@ msgid "" "def foo(arg: Optional[int] = None) -> None:\n" " ..." msgstr "" +"def foo(arg: Optional[int] = None) -> None:\n" +" ..." #: ../Doc/library/typing.rst:1143 msgid "" @@ -2132,6 +2517,9 @@ msgid "" " stats: ClassVar[dict[str, int]] = {} # class variable\n" " damage: int = 10 # instance variable" msgstr "" +"class Starship:\n" +" stats: ClassVar[dict[str, int]] = {} # variable de clase\n" +" damage: int = 10 # variable de instancia" # subscribed se substituye por niveles de subindice #: ../Doc/library/typing.rst:1245 @@ -2158,10 +2546,14 @@ msgid "" "enterprise_d.stats = {} # Error, setting class variable on instance\n" "Starship.stats = {} # This is OK" msgstr "" +"enterprise_d = Starship(3000)\n" +"enterprise_d.stats = {} # Error, establece variable de clase en la " +"instancia\n" +"Starship.stats = {} # Ésto está OK" #: ../Doc/library/typing.rst:1261 msgid ":data:`ClassVar` can now be nested in :data:`Final` and vice versa." -msgstr "" +msgstr "Ahora :data:`ClassVar` se puede anidar en :data:`Final` y viceversa." #: ../Doc/library/typing.rst:1265 msgid "Special typing construct to indicate final names to type checkers." @@ -2188,6 +2580,14 @@ msgid "" "class FastConnector(Connection):\n" " TIMEOUT = 1 # Error reported by type checker" msgstr "" +"MAX_SIZE: Final = 9000\n" +"MAX_SIZE += 1 # Error reportado por un verificador de tipos\n" +"\n" +"class Connection:\n" +" TIMEOUT: Final[int] = 10\n" +"\n" +"class FastConnector(Connection):\n" +" TIMEOUT = 1 # Error reportado por un verificador de tipos" #: ../Doc/library/typing.rst:1281 ../Doc/library/typing.rst:3081 msgid "" @@ -2199,7 +2599,7 @@ msgstr "" #: ../Doc/library/typing.rst:1288 msgid ":data:`Final` can now be nested in :data:`ClassVar` and vice versa." -msgstr "" +msgstr "Ahora :data:`Final` se puede anidar en :data:`ClassVar` y viceversa." #: ../Doc/library/typing.rst:1292 msgid "Special typing construct to mark a :class:`TypedDict` key as required." @@ -2228,13 +2628,12 @@ msgid "See :class:`TypedDict` and :pep:`655` for more details." msgstr "Véase :class:`TypedDict` y :pep:`655` para más detalle." #: ../Doc/library/typing.rst:1310 -#, fuzzy msgid "" "A special typing construct to mark an item of a :class:`TypedDict` as read-" "only." msgstr "" -"Construcción de tipado especial para marcar una clave :class:`TypedDict` " -"como requerida." +"Una construcción de tipificación especial para marcar un elemento de un :" +"class:`TypedDict` como de solo lectura." #: ../Doc/library/typing.rst:1314 msgid "" @@ -2246,16 +2645,22 @@ msgid "" " m[\"year\"] = 1999 # allowed\n" " m[\"title\"] = \"The Matrix\" # typechecker error" msgstr "" +"class Movie(TypedDict):\n" +" title: ReadOnly[str]\n" +" year: int\n" +"\n" +"def mutate_movie(m: Movie) -> None:\n" +" m[\"year\"] = 1999 # allowed\n" +" m[\"title\"] = \"The Matrix\" # error del verificador de tipos" #: ../Doc/library/typing.rst:1322 -#, fuzzy msgid "There is no runtime checking for this property." -msgstr "No hay ninguna comprobación en tiempo de ejecución de esta propiedad." +msgstr "" +"No hay ninguna comprobación en tiempo de ejecución para esta propiedad." #: ../Doc/library/typing.rst:1324 -#, fuzzy msgid "See :class:`TypedDict` and :pep:`705` for more details." -msgstr "Véase :class:`TypedDict` y :pep:`655` para más detalle." +msgstr "Vea :class:`TypedDict` y :pep:`705` para más detalle." #: ../Doc/library/typing.rst:1330 msgid "Special typing form to add context-specific metadata to an annotation." @@ -2307,15 +2712,14 @@ msgstr "" "deshabilita por completo la verificación de tipos para una función o clase." #: ../Doc/library/typing.rst:1350 -#, fuzzy msgid "" "The responsibility of how to interpret the metadata lies with the tool or " "library encountering an ``Annotated`` annotation. A tool or library " "encountering an ``Annotated`` type can scan through the metadata elements to " "determine if they are of interest (e.g., using :func:`isinstance`)." msgstr "" -"La responsabilidad de cómo interpretar los metadatos recae en la herramienta " -"o biblioteca que encuentre la anotación ``Annotated``. Una herramienta o " +"La responsabilidad de interpretar los metadatos recae en la herramienta o " +"biblioteca que encuentra una anotación ``Annotated``. Una herramienta o " "biblioteca que encuentra un tipo ``Annotated`` puede examinar los elementos " "de metadatos para determinar si son de interés (por ejemplo, utilizando :" "func:`isinstance`)." @@ -2339,6 +2743,13 @@ msgid "" "T1 = Annotated[int, ValueRange(-10, 5)]\n" "T2 = Annotated[T1, ValueRange(-20, 3)]" msgstr "" +"@dataclass\n" +"class ValueRange:\n" +" lo: int\n" +" hi: int\n" +"\n" +"T1 = Annotated[int, ValueRange(-10, 5)]\n" +"T2 = Annotated[T1, ValueRange(-20, 3)]" #: ../Doc/library/typing.rst:1371 msgid "Details of the syntax:" @@ -2364,6 +2775,11 @@ msgid "" "\n" "Annotated[int, ValueRange(3, 10), ctype(\"char\")]" msgstr "" +"@dataclass\n" +"class ctype:\n" +" kind: str\n" +"\n" +"Annotated[int, ValueRange(3, 10), ctype(\"char\")]" #: ../Doc/library/typing.rst:1384 msgid "" @@ -2397,6 +2813,9 @@ msgid "" " int, ctype(\"char\"), ValueRange(3, 10)\n" "]" msgstr "" +"assert Annotated[int, ValueRange(3, 10), ctype(\"char\")] != Annotated[\n" +" int, ctype(\"char\"), ValueRange(3, 10)\n" +"]" #: ../Doc/library/typing.rst:1398 msgid "" @@ -2413,6 +2832,10 @@ msgid "" " int, ValueRange(3, 10), ctype(\"char\")\n" "]" msgstr "" +"assert Annotated[Annotated[int, ValueRange(3, 10)], ctype(\"char\")] == " +"Annotated[\n" +" int, ValueRange(3, 10), ctype(\"char\")\n" +"]" #: ../Doc/library/typing.rst:1405 msgid "Duplicated metadata elements are not removed::" @@ -2424,6 +2847,9 @@ msgid "" " int, ValueRange(3, 10), ValueRange(3, 10)\n" "]" msgstr "" +"assert Annotated[int, ValueRange(3, 10)] != Annotated[\n" +" int, ValueRange(3, 10), ValueRange(3, 10)\n" +"]" #: ../Doc/library/typing.rst:1411 msgid "``Annotated`` can be used with nested and generic aliases:" @@ -2459,7 +2885,7 @@ msgstr "Esto sería equivalente a:" #: ../Doc/library/typing.rst:1431 msgid "Annotated[T1, T2, T3, ..., Ann1]" -msgstr "" +msgstr "Annotated[T1, T2, T3, ..., Ann1]" #: ../Doc/library/typing.rst:1433 msgid "" @@ -2487,6 +2913,13 @@ msgid "" ">>> get_type_hints(func, include_extras=True)\n" "{'x': typing.Annotated[int, 'metadata'], 'return': }" msgstr "" +">>> from typing import Annotated, get_type_hints\n" +">>> def func(x: Annotated[int, \"metadata\"]) -> None: pass\n" +"...\n" +">>> get_type_hints(func)\n" +"{'x': , 'return': }\n" +">>> get_type_hints(func, include_extras=True)\n" +"{'x': typing.Annotated[int, 'metadata'], 'return': }" #: ../Doc/library/typing.rst:1449 msgid "" @@ -2505,12 +2938,20 @@ msgid "" ">>> X.__metadata__\n" "('very', 'important', 'metadata')" msgstr "" +">>> from typing import Annotated\n" +">>> X = Annotated[int, \"very\", \"important\", \"metadata\"]\n" +">>> X\n" +"typing.Annotated[int, 'very', 'important', 'metadata']\n" +">>> X.__metadata__\n" +"('very', 'important', 'metadata')" #: ../Doc/library/typing.rst:1461 msgid "" "At runtime, if you want to retrieve the original type wrapped by " "``Annotated``, use the :attr:`!__origin__` attribute:" msgstr "" +"En tiempo de ejecución, si desea recuperar el tipo original envuelto por " +"``Annotated``, utilice el atributo :attr:`!__origin__`:" #: ../Doc/library/typing.rst:1464 msgid "" @@ -2519,16 +2960,24 @@ msgid "" ">>> Password.__origin__\n" "" msgstr "" +">>> from typing import Annotated, get_origin\n" +">>> Password = Annotated[str, \"secret\"]\n" +">>> Password.__origin__\n" +"" #: ../Doc/library/typing.rst:1471 msgid "Note that using :func:`get_origin` will return ``Annotated`` itself:" msgstr "" +"Tenga en cuenta que el uso de :func:`get_origin` devolverá el mismo " +"``Annotated``:" #: ../Doc/library/typing.rst:1473 msgid "" ">>> get_origin(Password)\n" "typing.Annotated" msgstr "" +">>> get_origin(Password)\n" +"typing.Annotated" #: ../Doc/library/typing.rst:1480 msgid ":pep:`593` - Flexible function and variable annotations" @@ -2539,28 +2988,26 @@ msgid "The PEP introducing ``Annotated`` to the standard library." msgstr "El PEP introduce ``Annotated`` en la biblioteca estándar." #: ../Doc/library/typing.rst:1488 ../Doc/library/typing.rst:1572 -#, fuzzy msgid "" "Special typing construct for marking user-defined type predicate functions." msgstr "" -"Construcción de tipado especial para marcar funciones de protección de tipo " -"definidas por el usuario." +"Construcción de tipificación especial para marcar funciones de predicado de " +"tipo definido por el usuario." #: ../Doc/library/typing.rst:1490 -#, fuzzy msgid "" "``TypeIs`` can be used to annotate the return type of a user-defined type " "predicate function. ``TypeIs`` only accepts a single type argument. At " "runtime, functions marked this way should return a boolean and take at least " "one positional argument." msgstr "" -"``TypeGuard`` se puede utilizar para anotar el tipo de retorno de una " -"función de protección de tipo definida por el usuario. ``TypeGuard`` solo " -"acepta un único argumento de tipo. En tiempo de ejecución, las funciones " -"marcadas de esta manera deben devolver un valor booleano." +"``TypeIs`` se puede utilizar para anotar el tipo de retorno de una función " +"de predicado de tipo definida por el usuario. ``TypeIs`` solo acepta un " +"único argumento de tipo. En tiempo de ejecución, las funciones marcadas de " +"esta manera deben devolver un valor booleano y tomar al menos un argumento " +"posicional." #: ../Doc/library/typing.rst:1495 -#, fuzzy msgid "" "``TypeIs`` aims to benefit *type narrowing* -- a technique used by static " "type checkers to determine a more precise type of an expression within a " @@ -2569,12 +3016,12 @@ msgid "" "conditional expression here is sometimes referred to as a \"type " "predicate\"::" msgstr "" -"``TypeGuard`` tiene como objetivo beneficiar a *type narrowing*, una técnica " -"utilizada por los validadores de tipo estático para determinar un tipo más " -"preciso de una expresión dentro del flujo de código de un programa. Por lo " -"general, el estrechamiento de tipos se realiza analizando el flujo de código " -"condicional y aplicando el estrechamiento a un bloque de código. La " -"expresión condicional aquí a veces se denomina \"protección de tipo\":" +"``TypeIs`` tiene como objetivo beneficiar a *type narrowing*, una técnica " +"utilizada por los verificadores de tipos estáticos para determinar un tipo " +"más preciso de una expresión dentro del flujo de código de un programa. Por " +"lo general, la restricción de tipos se realiza analizando el flujo de código " +"condicional y aplicando la restricción a un bloque de código. La expresión " +"condicional aquí a veces se denomina \"predicado de tipo\":" #: ../Doc/library/typing.rst:1501 msgid "" @@ -2598,37 +3045,42 @@ msgid "" "incompatible (e.g., ``list[object]`` to ``list[int]``) or when the function " "does not return ``True`` for all instances of the narrowed type." msgstr "" +"A veces sería conveniente utilizar una función booleana definida por el " +"usuario como predicado de tipo. Dicha función debería utilizar " +"``TypeIs[...]`` o :data:`TypeGuard` como su tipo de retorno para alertar a " +"los verificadores de tipos estáticos sobre esta intención. ``TypeIs`` suele " +"tener un comportamiento más intuitivo que ``TypeGuard``, pero no se puede " +"utilizar cuando los tipos de entrada y salida son incompatibles (por " +"ejemplo, ``list[object]`` a ``list[int]``) o cuando la función no devuelve " +"``True`` para todas las instancias del tipo restringido." #: ../Doc/library/typing.rst:1518 -#, fuzzy msgid "" "Using ``-> TypeIs[NarrowedType]`` tells the static type checker that for a " "given function:" msgstr "" -"El uso de ``-> TypeGuard`` le dice al validador de tipo estático que para " -"una función determinada:" +"El uso de ``-> TypeIs[NarrowedType]`` le indica al verificador de tipo " +"estático que para una función determinada:" #: ../Doc/library/typing.rst:1521 ../Doc/library/typing.rst:1582 msgid "The return value is a boolean." msgstr "El valor de retorno es un booleano." #: ../Doc/library/typing.rst:1522 -#, fuzzy msgid "" "If the return value is ``True``, the type of its argument is the " "intersection of the argument's original type and ``NarrowedType``." msgstr "" -"Si el valor de retorno es ``True``, el tipo de su argumento es el tipo " -"dentro de ``TypeGuard``." +"Si el valor de retorno es ``True``, el tipo de su argumento es la " +"intersección del tipo original del argumento y ``NarrowedType``." #: ../Doc/library/typing.rst:1524 -#, fuzzy msgid "" "If the return value is ``False``, the type of its argument is narrowed to " "exclude ``NarrowedType``." msgstr "" -"Si el valor de retorno es ``True``, el tipo de su argumento es el tipo " -"dentro de ``TypeGuard``." +"Si el valor de retorno es ``False``, el tipo de su argumento se limita para " +"excluir ``NarrowedType``." #: ../Doc/library/typing.rst:1529 msgid "" @@ -2653,6 +3105,26 @@ msgid "" " # so only ``Unrelated`` is left.\n" " assert_type(arg, Unrelated)" msgstr "" +"from typing import assert_type, final, TypeIs\n" +"\n" +"class Parent: pass\n" +"class Child(Parent): pass\n" +"@final\n" +"class Unrelated: pass\n" +"\n" +"def is_parent(val: object) -> TypeIs[Parent]:\n" +" return isinstance(val, Parent)\n" +"\n" +"def run(arg: Child | Unrelated):\n" +" if is_parent(arg):\n" +" # El tipo de ``arg`` es reducido a la intersección\n" +" # de ``Parent`` y ``Child``, lo cual es equivalente a\n" +" # ``Child``.\n" +" assert_type(arg, Child)\n" +" else:\n" +" # El tipo de ``arg`` es reducido para excluir ``Parent``,\n" +" # para que solo quede ``Unrelated``.\n" +" assert_type(arg, Unrelated)" #: ../Doc/library/typing.rst:1550 msgid "" @@ -2662,37 +3134,40 @@ msgid "" "behavior in the type system; it is the user's responsibility to write such " "functions in a type-safe manner." msgstr "" +"El tipo dentro de ``TypeIs`` debe ser coherente con el tipo del argumento de " +"la función; si no lo es, los comprobadores de tipos estáticos generarán un " +"error. Una función ``TypeIs`` escrita incorrectamente puede provocar un " +"comportamiento incorrecto en el sistema de tipos; es responsabilidad del " +"usuario escribir dichas funciones de manera segura." #: ../Doc/library/typing.rst:1556 -#, fuzzy msgid "" "If a ``TypeIs`` function is a class or instance method, then the type in " "``TypeIs`` maps to the type of the second parameter (after ``cls`` or " "``self``)." msgstr "" -"Si ``is_str_list`` es un método de clase o instancia, entonces el tipo en " -"``TypeGuard`` se asigna al tipo del segundo parámetro después de ``cls`` o " -"``self``." +"Si una función ``TypeIs`` es un método de clase o instancia, entonces el " +"tipo en ``TypeIs`` se asigna al tipo del segundo parámetro (después de " +"``cls`` o ``self``)." #: ../Doc/library/typing.rst:1560 -#, fuzzy msgid "" "In short, the form ``def foo(arg: TypeA) -> TypeIs[TypeB]: ...``, means that " "if ``foo(arg)`` returns ``True``, then ``arg`` is an instance of ``TypeB``, " "and if it returns ``False``, it is not an instance of ``TypeB``." msgstr "" -"En resumen, la forma ``def foo(arg: TypeA) -> TypeGuard[TypeB]: ...`` " -"significa que si ``foo(arg)`` retorna ``True``, entonces ``arg`` se estrecha " -"de ``TypeA`` a ``TypeB``." +"En resumen, la forma ``def foo(arg: TypeA) -> TypeIs[TypeB]: ...``, " +"significa que si ``foo(arg)`` devuelve ``True``, entonces ``arg`` es una " +"instancia de ``TypeB``, y si devuelve ``False``, no es una instancia de " +"``TypeB``." #: ../Doc/library/typing.rst:1564 -#, fuzzy msgid "" "``TypeIs`` also works with type variables. For more information, see :pep:" "`742` (Narrowing types with ``TypeIs``)." msgstr "" -"``TypeGuard`` también funciona con variables de tipo. Véase :pep:`647` para " -"más detalles." +"``TypeIs`` también funciona con variables de tipo. Para obtener más " +"información, consulte :pep:`742` (Restringir tipos con ``TypeIs``)." #: ../Doc/library/typing.rst:1574 msgid "" @@ -2701,6 +3176,11 @@ msgid "" "similarly to :data:`TypeIs`, but has subtly different effects on type " "checking behavior (see below)." msgstr "" +"Las funciones de predicado de tipo son funciones definidas por el usuario " +"que indican si su argumento es una instancia de un tipo en particular. " +"``TypeGuard`` funciona de manera similar a :data:`TypeIs`, pero tiene " +"efectos ligeramente diferentes en el comportamiento de verificación de tipo " +"(ver a continuación)." #: ../Doc/library/typing.rst:1579 msgid "" @@ -2740,24 +3220,33 @@ msgid "" " # Type of ``val`` remains as ``list[object]``.\n" " print(\"Not a list of strings!\")" msgstr "" +"def is_str_list(val: list[object]) -> TypeGuard[list[str]]:\n" +" '''Determines whether all objects in the list are strings'''\n" +" return all(isinstance(x, str) for x in val)\n" +"\n" +"def func1(val: list[object]):\n" +" if is_str_list(val):\n" +" # El tipo de ``val`` es reducido a ``list[str]``.\n" +" print(\" \".join(val))\n" +" else:\n" +" # El tipo de ``val`` se mantiene como ``list[object]``.\n" +" print(\"Not a list of strings!\")" #: ../Doc/library/typing.rst:1602 msgid "``TypeIs`` and ``TypeGuard`` differ in the following ways:" -msgstr "" +msgstr "``TypeIs`` y ``TypeGuard`` se diferencian en los siguientes aspectos:" #: ../Doc/library/typing.rst:1604 -#, fuzzy msgid "" "``TypeIs`` requires the narrowed type to be a subtype of the input type, " "while ``TypeGuard`` does not. The main reason is to allow for things like " "narrowing ``list[object]`` to ``list[str]`` even though the latter is not a " "subtype of the former, since ``list`` is invariant." msgstr "" -"No es necesario que ``TypeB`` sea una forma más estrecha de ``TypeA``; " -"incluso puede ser una forma más amplia. La razón principal es permitir cosas " -"como reducir ``List[object]`` a ``List[str]`` aunque este último no sea un " -"subtipo del primero, ya que ``List`` es invariante. La responsabilidad de " -"escribir protecciones de tipo seguras se deja al usuario." +"``TypeIs`` requiere que el tipo restringido sea un subtipo del tipo de " +"entrada, mientras que ``TypeGuard`` no lo requiere. La razón principal es " +"permitir cosas como restringir ``list[object]`` a ``list[str]``, aunque este " +"último no sea un subtipo del primero, ya que ``list`` es invariante." #: ../Doc/library/typing.rst:1608 msgid "" @@ -2767,6 +3256,12 @@ msgid "" "combining the previously known type of the variable with the ``TypeIs`` " "type. (Technically, this is known as an intersection type.)" msgstr "" +"Cuando una función ``TypeGuard`` devuelve ``True``, los verificadores de " +"tipo limitan el tipo de la variable exactamente al tipo ``TypeGuard``. " +"Cuando una función ``TypeIs`` devuelve ``True``, los verificadores de tipo " +"pueden inferir un tipo más preciso combinando el tipo conocido previamente " +"de la variable con el tipo ``TypeIs``. (Técnicamente, esto se conoce como un " +"tipo de intersección)." #: ../Doc/library/typing.rst:1612 msgid "" @@ -2775,6 +3270,10 @@ msgid "" "``False``, type checkers can narrow the type of the variable to exclude the " "``TypeIs`` type." msgstr "" +"Cuando una función ``TypeGuard`` devuelve ``False``, los verificadores de " +"tipo no pueden limitar el tipo de la variable en absoluto. Cuando una " +"función ``TypeIs`` devuelve ``False``, los verificadores de tipo pueden " +"limitar el tipo de la variable para excluir el tipo ``TypeIs``." #: ../Doc/library/typing.rst:1621 msgid "Typing operator to conceptually mark an object as having been unpacked." @@ -2783,15 +3282,14 @@ msgstr "" "desempaquetado." #: ../Doc/library/typing.rst:1623 -#, fuzzy msgid "" "For example, using the unpack operator ``*`` on a :ref:`type variable tuple " "` is equivalent to using ``Unpack`` to mark the type variable " "tuple as having been unpacked::" msgstr "" -"Por ejemplo, usar el operador de desempaquetamiento ``*`` en una :class:" -"`tupla de variable de tipo ` es equivalente a usar ``Unpack`` " -"para marcar la tupla de variable de tipo como desempaquetada::" +"Por ejemplo, usar el operador de descompresión ``*`` en un :ref:`type " +"variable tuple ` es equivalente a usar ``Unpack`` para marcar " +"la tupla de variable de tipo como descomprimida:" #: ../Doc/library/typing.rst:1627 msgid "" @@ -2800,6 +3298,10 @@ msgid "" "# Effectively does:\n" "tup: tuple[Unpack[Ts]]" msgstr "" +"Ts = TypeVarTuple('Ts')\n" +"tup: tuple[*Ts]\n" +"# Effectively does:\n" +"tup: tuple[Unpack[Ts]]" #: ../Doc/library/typing.rst:1632 msgid "" @@ -2898,6 +3400,10 @@ msgid "" " ...\n" " # Etc." msgstr "" +"class Mapping[KT, VT]:\n" +" def __getitem__(self, key: KT) -> VT:\n" +" ...\n" +" # Etc." #: ../Doc/library/typing.rst:1687 msgid "" @@ -2920,6 +3426,11 @@ msgid "" " except KeyError:\n" " return default" msgstr "" +"def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y:\n" +" try:\n" +" return mapping[key]\n" +" except KeyError:\n" +" return default" #: ../Doc/library/typing.rst:1699 msgid "" @@ -2949,6 +3460,13 @@ msgid "" " ...\n" " # Etc." msgstr "" +"KT = TypeVar('KT')\n" +"VT = TypeVar('VT')\n" +"\n" +"class Mapping(Generic[KT, VT]):\n" +" def __getitem__(self, key: KT) -> VT:\n" +" ...\n" +" # Etc." #: ../Doc/library/typing.rst:1719 msgid "Type variable." @@ -2970,6 +3488,8 @@ msgid "" "class Sequence[T]: # T is a TypeVar\n" " ..." msgstr "" +"class Sequence[T]: # T is a TypeVar\n" +" ..." #: ../Doc/library/typing.rst:1729 msgid "" @@ -2988,6 +3508,13 @@ msgid "" "str or bytes\n" " ..." msgstr "" +"class StrSequence[S: str]: # S es un TypeVar ligado a str\n" +" ...\n" +"\n" +"\n" +"class StrOrBytesSequence[A: (str, bytes)]: # A es un TypeVar limitado a str " +"o bytes\n" +" ..." #: ../Doc/library/typing.rst:1739 msgid "" @@ -3003,6 +3530,9 @@ msgid "" "S = TypeVar('S', bound=str) # Can be any subtype of str\n" "A = TypeVar('A', str, bytes) # Must be exactly str or bytes" msgstr "" +"T = TypeVar('T') # Puede ser cualquier cosa\n" +"S = TypeVar('S', bound=str) # Puede ser cualquier subtipo de str\n" +"A = TypeVar('A', str, bytes) # Tiene que ser exactamente str o bytes" #: ../Doc/library/typing.rst:1745 msgid "" @@ -3034,6 +3564,20 @@ msgid "" " \"\"\"Add two strings or bytes objects together.\"\"\"\n" " return x + y" msgstr "" +"def repeat[T](x: T, n: int) -> Sequence[T]:\n" +" \"\"\"Return a list containing n references to x.\"\"\"\n" +" return [x]*n\n" +"\n" +"\n" +"def print_capitalized[S: str](x: S) -> S:\n" +" \"\"\"Print x capitalized, and return x.\"\"\"\n" +" print(x.capitalize())\n" +" return x\n" +"\n" +"\n" +"def concatenate[A: (str, bytes)](x: A, y: A) -> A:\n" +" \"\"\"Add two strings or bytes objects together.\"\"\"\n" +" return x + y" #: ../Doc/library/typing.rst:1766 msgid "" @@ -3085,6 +3629,16 @@ msgid "" "\n" "z = print_capitalized(45) # error: int is not a subtype of str" msgstr "" +"x = print_capitalized('a string')\n" +"reveal_type(x) # el tipo revelado es str\n" +"\n" +"class StringSubclass(str):\n" +" pass\n" +"\n" +"y = print_capitalized(StringSubclass('another string'))\n" +"reveal_type(y) # revealed type is StringSubclass\n" +"\n" +"z = print_capitalized(45) # error: int no es un subtipo de str" #: ../Doc/library/typing.rst:1792 msgid "" @@ -3126,6 +3680,14 @@ msgid "" "c = concatenate('one', b'two') # error: type variable 'A' can be either str " "or bytes in a function call, but not both" msgstr "" +"a = concatenate('one', 'two')\n" +"reveal_type(a) # tipo revelado es str\n" +"\n" +"b = concatenate(StringSubclass('one'), StringSubclass('two'))\n" +"reveal_type(b) # tipo revelado es str, a pesar que se pasa StringSubclass\n" +"\n" +"c = concatenate('one', b'two') # error: la variable de tipo 'A' puede ser " +"str o bytes en una llamada a función, pero no ambas" #: ../Doc/library/typing.rst:1815 msgid "At runtime, ``isinstance(x, T)`` will raise :exc:`TypeError`." @@ -3185,6 +3747,8 @@ msgid "" "The default value of the type variable, or :data:`typing.NoDefault` if it " "has no default." msgstr "" +"El valor predeterminado de la variable de tipo, o :data:`typing.NoDefault` " +"si no tiene valor predeterminado." #: ../Doc/library/typing.rst:1864 msgid "" @@ -3193,6 +3757,10 @@ msgid "" "NoDefault` singleton, except that it does not force evaluation of the :ref:" "`lazily evaluated ` default value." msgstr "" +"Devuelve si la variable de tipo tiene o no un valor predeterminado. Esto es " +"equivalente a verificar si :attr:`__default__` no es el singleton :data:" +"`typing.NoDefault`, excepto que no fuerza la evaluación del valor " +"predeterminado :ref:`lazily evaluated `." #: ../Doc/library/typing.rst:1873 msgid "" @@ -3206,18 +3774,16 @@ msgstr "" #: ../Doc/library/typing.rst:1879 ../Doc/library/typing.rst:2018 #: ../Doc/library/typing.rst:2120 -#, fuzzy msgid "Support for default values was added." -msgstr "Soporte añadido para valores por defecto, métodos y *docstrings*." +msgstr "Se agregó soporte para valores predeterminados." #: ../Doc/library/typing.rst:1885 -#, fuzzy msgid "" "Type variable tuple. A specialized form of :ref:`type variable ` " "that enables *variadic* generics." msgstr "" -"Tupla de variables de tipo. Una versión especializada de :class:`type " -"variables ` que permite genéricos *variádicos*." +"Tupla de variable de tipo. Forma especializada de :ref:`type variable " +"` que habilita genéricos de *variadic*." #: ../Doc/library/typing.rst:1888 msgid "" @@ -3234,6 +3800,9 @@ msgid "" "T]:\n" " return (*tup[1:], tup[0])" msgstr "" +"def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, " +"T]:\n" +" return (*tup[1:], tup[0])" #: ../Doc/library/typing.rst:1894 msgid "Or by explicitly invoking the ``TypeVarTuple`` constructor::" @@ -3247,6 +3816,11 @@ msgid "" "def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:\n" " return (*tup[1:], tup[0])" msgstr "" +"T = TypeVar(\"T\")\n" +"Ts = TypeVarTuple(\"Ts\")\n" +"\n" +"def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:\n" +" return (*tup[1:], tup[0])" #: ../Doc/library/typing.rst:1902 msgid "" @@ -3328,6 +3902,10 @@ msgid "" " def __abs__(self) -> \"Array[*Shape]\": ...\n" " def get_shape(self) -> tuple[*Shape]: ..." msgstr "" +"class Array[*Shape]:\n" +" def __getitem__(self, key: tuple[*Shape]) -> float: ...\n" +" def __abs__(self) -> \"Array[*Shape]\": ...\n" +" def get_shape(self) -> tuple[*Shape]: ..." #: ../Doc/library/typing.rst:1947 msgid "" @@ -3365,6 +3943,9 @@ msgid "" "class Array[*Shape, *Shape]: # Not valid\n" " pass" msgstr "" +"x: tuple[*Ts, *Ts] # Not valid\n" +"class Array[*Shape, *Shape]: # Not valid\n" +" pass" #: ../Doc/library/typing.rst:1970 msgid "" @@ -3383,6 +3964,12 @@ msgid "" " ...\n" " callback(*args)" msgstr "" +"def call_soon[*Ts](\n" +" callback: Callable[[*Ts], None],\n" +" *args: *Ts\n" +") -> None:\n" +" ...\n" +" callback(*args)" #: ../Doc/library/typing.rst:1980 msgid "" @@ -3414,6 +4001,8 @@ msgid "" "The default value of the type variable tuple, or :data:`typing.NoDefault` if " "it has no default." msgstr "" +"El valor predeterminado de la variable de tipo tupla, o :data:`typing." +"NoDefault` si no tiene valor predeterminado." #: ../Doc/library/typing.rst:2002 msgid "" @@ -3422,6 +4011,10 @@ msgid "" "NoDefault` singleton, except that it does not force evaluation of the :ref:" "`lazily evaluated ` default value." msgstr "" +"Devuelve si la variable de tipo tupla tiene o no un valor predeterminado. " +"Esto es equivalente a verificar si :attr:`__default__` no es el singleton :" +"data:`typing.NoDefault`, excepto que no fuerza la evaluación del valor " +"predeterminado :ref:`lazily evaluated `." #: ../Doc/library/typing.rst:2013 msgid "" @@ -3432,13 +4025,12 @@ msgstr "" "de :ref:`parámetros de tipo ` introducida por :pep:`695`." #: ../Doc/library/typing.rst:2022 -#, fuzzy msgid "" "Parameter specification variable. A specialized version of :ref:`type " "variables `." msgstr "" -"Variable de especificación de parámetros. Una versión especializada de :" -"class:`type variables `." +"Variable de especificación de parámetros. Versión especializada de :ref:" +"`type variables `." #: ../Doc/library/typing.rst:2025 msgid "" @@ -3451,7 +4043,7 @@ msgstr "" #: ../Doc/library/typing.rst:2028 msgid "type IntFunc[**P] = Callable[P, int]" -msgstr "" +msgstr "type IntFunc[**P] = Callable[P, int]" #: ../Doc/library/typing.rst:2030 msgid "" @@ -3463,7 +4055,7 @@ msgstr "" #: ../Doc/library/typing.rst:2033 msgid "P = ParamSpec('P')" -msgstr "" +msgstr "P = ParamSpec('P')" #: ../Doc/library/typing.rst:2035 msgid "" @@ -3511,7 +4103,21 @@ msgid "" "def add_two(x: float, y: float) -> float:\n" " '''Add two numbers together.'''\n" " return x + y" -msgstr "" +msgstr "" +"from collections.abc import Callable\n" +"import logging\n" +"\n" +"def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]:\n" +" '''A type-safe decorator to add logging to a function.'''\n" +" def inner(*args: P.args, **kwargs: P.kwargs) -> T:\n" +" logging.info(f'{f.__name__} was called')\n" +" return f(*args, **kwargs)\n" +" return inner\n" +"\n" +"@add_logging\n" +"def add_two(x: float, y: float) -> float:\n" +" '''Add two numbers together.'''\n" +" return x + y" #: ../Doc/library/typing.rst:2062 msgid "" @@ -3573,6 +4179,8 @@ msgid "" "The default value of the parameter specification, or :data:`typing." "NoDefault` if it has no default." msgstr "" +"El valor predeterminado de la especificación del parámetro, o :data:`typing." +"NoDefault` si no tiene valor predeterminado." #: ../Doc/library/typing.rst:2098 msgid "" @@ -3581,6 +4189,10 @@ msgid "" "`typing.NoDefault` singleton, except that it does not force evaluation of " "the :ref:`lazily evaluated ` default value." msgstr "" +"Devuelve si la especificación del parámetro tiene o no un valor " +"predeterminado. Esto es equivalente a verificar si :attr:`__default__` no es " +"el singleton :data:`typing.NoDefault`, excepto que no fuerza la evaluación " +"del valor predeterminado :ref:`lazily evaluated `." #: ../Doc/library/typing.rst:2105 msgid "" @@ -3647,6 +4259,12 @@ msgid "" ">>> get_origin(P.kwargs) is P\n" "True" msgstr "" +">>> from typing import ParamSpec, get_origin\n" +">>> P = ParamSpec(\"P\")\n" +">>> get_origin(P.args) is P\n" +"True\n" +">>> get_origin(P.kwargs) is P\n" +"True" #: ../Doc/library/typing.rst:2157 msgid "The type of type aliases created through the :keyword:`type` statement." @@ -3659,6 +4277,9 @@ msgid "" ">>> type(Alias)\n" "" msgstr "" +">>> type Alias = int\n" +">>> type(Alias)\n" +"" #: ../Doc/library/typing.rst:2171 msgid "The name of the type alias:" @@ -3670,6 +4291,9 @@ msgid "" ">>> Alias.__name__\n" "'Alias'" msgstr "" +">>> type Alias = int\n" +">>> Alias.__name__\n" +"'Alias'" #: ../Doc/library/typing.rst:2181 msgid "The module in which the type alias was defined::" @@ -3681,6 +4305,9 @@ msgid "" ">>> Alias.__module__\n" "'__main__'" msgstr "" +">>> type Alias = int\n" +">>> Alias.__module__\n" +"'__main__'" #: ../Doc/library/typing.rst:2189 msgid "" @@ -3699,6 +4326,12 @@ msgid "" ">>> NotGeneric.__type_params__\n" "()" msgstr "" +">>> type ListOrSet[T] = list[T] | set[T]\n" +">>> ListOrSet.__type_params__\n" +"(T,)\n" +">>> type NotGeneric = int\n" +">>> NotGeneric.__type_params__\n" +"()" #: ../Doc/library/typing.rst:2203 msgid "" @@ -3723,6 +4356,16 @@ msgid "" ">>> Recursive.__value__\n" "Mutually" msgstr "" +">>> type Mutually = Recursive\n" +">>> type Recursive = Mutually\n" +">>> Mutually\n" +"Mutually\n" +">>> Recursive\n" +"Recursive\n" +">>> Mutually.__value__\n" +"Recursive\n" +">>> Recursive.__value__\n" +"Mutually" #: ../Doc/library/typing.rst:2221 msgid "Other special directives" @@ -3753,6 +4396,9 @@ msgid "" " name: str\n" " id: int" msgstr "" +"class Employee(NamedTuple):\n" +" name: str\n" +" id: int" #: ../Doc/library/typing.rst:2237 msgid "This is equivalent to::" @@ -3760,7 +4406,7 @@ msgstr "Esto es equivalente a::" #: ../Doc/library/typing.rst:2239 msgid "Employee = collections.namedtuple('Employee', ['name', 'id'])" -msgstr "" +msgstr "Employee = collections.namedtuple('Employee', ['name', 'id'])" #: ../Doc/library/typing.rst:2241 msgid "" @@ -3778,6 +4424,12 @@ msgid "" "employee = Employee('Guido')\n" "assert employee.id == 3" msgstr "" +"class Employee(NamedTuple):\n" +" name: str\n" +" id: int = 3\n" +"\n" +"employee = Employee('Guido')\n" +"assert employee.id == 3" #: ../Doc/library/typing.rst:2250 msgid "" @@ -3815,6 +4467,13 @@ msgid "" " def __repr__(self) -> str:\n" " return f''" msgstr "" +"class Employee(NamedTuple):\n" +" \"\"\"Represents an employee.\"\"\"\n" +" name: str\n" +" id: int = 3\n" +"\n" +" def __repr__(self) -> str:\n" +" return f''" #: ../Doc/library/typing.rst:2268 msgid "``NamedTuple`` subclasses can be generic::" @@ -3826,6 +4485,9 @@ msgid "" " key: T\n" " group: list[T]" msgstr "" +"class Group[T](NamedTuple):\n" +" key: T\n" +" group: list[T]" #: ../Doc/library/typing.rst:2274 msgid "Backward-compatible usage::" @@ -3843,6 +4505,15 @@ msgid "" "# A functional syntax is also supported\n" "Employee = NamedTuple('Employee', [('name', str), ('id', int)])" msgstr "" +"# Para crear un NamedTuple genérico en Python 3.11\n" +"T = TypeVar(\"T\")\n" +"\n" +"class Group(NamedTuple, Generic[T]):\n" +" key: T\n" +" group: list[T]\n" +"\n" +"# También se admite una sintaxis funcional\n" +"Employee = NamedTuple('Employee', [('name', str), ('id', int)])" #: ../Doc/library/typing.rst:2286 msgid "Added support for :pep:`526` variable annotation syntax." @@ -3880,6 +4551,10 @@ msgid "" "(``NT = NamedTuple(\"NT\", x=int)``) is deprecated, and will be disallowed " "in 3.15. Use the class-based syntax or the functional syntax instead." msgstr "" +"La sintaxis de argumentos de palabras clave no documentada para crear clases " +"NamedTuple (``NT = NamedTuple(\"NT\", x=int)``) está obsoleta y no se " +"permitirá en la versión 3.15. En su lugar, utilice la sintaxis basada en " +"clases o la sintaxis funcional." #: ../Doc/library/typing.rst:2308 msgid "" @@ -3890,6 +4565,12 @@ msgid "" "Python 3.15. To create a NamedTuple class with 0 fields, use ``class " "NT(NamedTuple): pass`` or ``NT = NamedTuple(\"NT\", [])``." msgstr "" +"Al utilizar la sintaxis funcional para crear una clase NamedTuple, no se " +"permite pasar un valor al parámetro 'campos' (``NT = NamedTuple(\"NT\")``). " +"También se permite pasar ``None`` al parámetro 'campos' (``NT = " +"NamedTuple(\"NT\", None)``). Ambos métodos no estarán permitidos en Python " +"3.15. Para crear una clase NamedTuple con 0 campos, utilice ``class " +"NT(NamedTuple): pass`` o ``NT = NamedTuple(\"NT\", [])``." #: ../Doc/library/typing.rst:2318 msgid "Helper class to create low-overhead :ref:`distinct types `." @@ -3912,6 +4593,9 @@ msgid "" "first_user = UserId(1) # \"UserId\" returns the argument unchanged at " "runtime" msgstr "" +"UserId = NewType('UserId', int) # Declara el NewType \"UserId\"\n" +"first_user = UserId(1) # \"UserId\" retorna el argumento sin cambios en " +"runtime" #: ../Doc/library/typing.rst:2330 msgid "The module in which the new type is defined." @@ -3943,6 +4627,9 @@ msgid "" " def meth(self) -> int:\n" " ..." msgstr "" +"class Proto(Protocol):\n" +" def meth(self) -> int:\n" +" ..." #: ../Doc/library/typing.rst:2355 msgid "" @@ -3963,6 +4650,14 @@ msgid "" "\n" "func(C()) # Passes static type check" msgstr "" +"class C:\n" +" def meth(self) -> int:\n" +" return 0\n" +"\n" +"def func(x: Proto) -> int:\n" +" return x.meth()\n" +"\n" +"func(C()) # Pasa la verificación de tipos estática" #: ../Doc/library/typing.rst:2367 msgid "" @@ -3986,6 +4681,9 @@ msgid "" " def meth(self) -> T:\n" " ..." msgstr "" +"class GenProto[T](Protocol):\n" +" def meth(self) -> T:\n" +" ..." #: ../Doc/library/typing.rst:2378 msgid "" @@ -4003,6 +4701,11 @@ msgid "" " def meth(self) -> T:\n" " ..." msgstr "" +"T = TypeVar(\"T\")\n" +"\n" +"class GenProto(Protocol[T]):\n" +" def meth(self) -> T:\n" +" ..." #: ../Doc/library/typing.rst:2391 msgid "Mark a protocol class as a runtime protocol." @@ -4039,6 +4742,18 @@ msgid "" "import threading\n" "assert isinstance(threading.Thread(name='Bob'), Named)" msgstr "" +"@runtime_checkable\n" +"class Closable(Protocol):\n" +" def close(self): ...\n" +"\n" +"assert isinstance(open('/some/file'), Closable)\n" +"\n" +"@runtime_checkable\n" +"class Named(Protocol):\n" +" name: str\n" +"\n" +"import threading\n" +"assert isinstance(threading.Thread(name='Bob'), Named)" #: ../Doc/library/typing.rst:2413 msgid "" @@ -4138,27 +4853,38 @@ msgid "" "\n" "assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')" msgstr "" +"class Point2D(TypedDict):\n" +" x: int\n" +" y: int\n" +" label: str\n" +"\n" +"a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK\n" +"b: Point2D = {'z': 3, 'label': 'bad'} # Falla la verificación de " +"tipos\n" +"\n" +"assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')" #: ../Doc/library/typing.rst:2471 msgid "" "An alternative way to create a ``TypedDict`` is by using function-call " "syntax. The second argument must be a literal :class:`dict`::" msgstr "" +"Una forma alternativa de crear un ``TypedDict`` es mediante la sintaxis de " +"llamada de función. El segundo argumento debe ser un :class:`dict` literal::" #: ../Doc/library/typing.rst:2474 msgid "Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})" -msgstr "" +msgstr "Punto2D = TypedDict('Punto2D', {'x': int, 'y': int, 'etiqueta': str})" #: ../Doc/library/typing.rst:2476 -#, fuzzy msgid "" "This functional syntax allows defining keys which are not valid :ref:" "`identifiers `, for example because they are keywords or " "contain hyphens::" msgstr "" -"También es preferible el uso de la sintaxis funcional cuando cualquiera de " -"las llaves no sean :ref:`identifiers` válidos, por ejemplo " -"porque son palabras clave o contienen guiones. Ejemplo::" +"Esta sintaxis funcional permite definir claves que no son válidas :ref:" +"`identifiers `, por ejemplo porque son palabras clave o " +"contienen guiones:" #: ../Doc/library/typing.rst:2480 msgid "" @@ -4217,6 +4943,12 @@ msgid "" "# Alternative syntax\n" "Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False)" msgstr "" +"class Point2D(TypedDict, total=False):\n" +" x: int\n" +" y: int\n" +"\n" +"# Sintaxis alternativa\n" +"Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False)" #: ../Doc/library/typing.rst:2512 msgid "" @@ -4267,6 +4999,8 @@ msgid "" "class Point3D(Point2D):\n" " z: int" msgstr "" +"class Point3D(Point2D):\n" +" z: int" #: ../Doc/library/typing.rst:2539 msgid "" @@ -4283,6 +5017,10 @@ msgid "" " y: int\n" " z: int" msgstr "" +"class Point3D(TypedDict):\n" +" x: int\n" +" y: int\n" +" z: int" #: ../Doc/library/typing.rst:2547 msgid "" @@ -4306,6 +5044,17 @@ msgid "" "\n" "class XZ(X, Z): pass # raises TypeError" msgstr "" +"class X(TypedDict):\n" +" x: int\n" +"\n" +"class Y(TypedDict):\n" +" y: int\n" +"\n" +"class Z(object): pass # Una clase no-TypedDict\n" +"\n" +"class XY(X, Y): pass # OK\n" +"\n" +"class XZ(X, Z): pass # lanza TypeError" #: ../Doc/library/typing.rst:2562 msgid "A ``TypedDict`` can be generic::" @@ -4317,6 +5066,9 @@ msgid "" " key: T\n" " group: list[T]" msgstr "" +"class Group[T](TypedDict):\n" +" key: T\n" +" group: list[T]" #: ../Doc/library/typing.rst:2568 msgid "" @@ -4334,6 +5086,11 @@ msgid "" " key: T\n" " group: list[T]" msgstr "" +"T = TypeVar(\"T\")\n" +"\n" +"class Group(TypedDict, Generic[T]):\n" +" key: T\n" +" group: list[T]" #: ../Doc/library/typing.rst:2579 msgid "" @@ -4366,6 +5123,16 @@ msgid "" ">>> Point3D.__total__\n" "True" msgstr "" +">>> from typing import TypedDict\n" +">>> class Point2D(TypedDict): pass\n" +">>> Point2D.__total__\n" +"True\n" +">>> class Point2D(TypedDict, total=False): pass\n" +">>> Point2D.__total__\n" +"False\n" +">>> class Point3D(Point2D): pass\n" +">>> Point3D.__total__\n" +"True" #: ../Doc/library/typing.rst:2601 msgid "" @@ -4377,6 +5144,12 @@ msgid "" "use :attr:`__required_keys__` and :attr:`__optional_keys__` for " "introspection." msgstr "" +"Este atributo refleja el valor del argumento ``total`` de la clase " +"``TypedDict`` actual, no si la clase es semánticamente total. Por ejemplo, " +"una ``TypedDict`` con ``__total__`` establecida en ``True`` puede tener " +"claves marcadas con :data:`NotRequired`, o puede heredar de otra " +"``TypedDict`` con ``total=False``. Por lo tanto, generalmente es mejor usar :" +"attr:`__required_keys__` y :attr:`__optional_keys__` para la introspección." #: ../Doc/library/typing.rst:2614 msgid "" @@ -4426,6 +5199,17 @@ msgid "" ">>> Point3D.__optional_keys__ == frozenset({'x', 'y'})\n" "True" msgstr "" +">>> class Point2D(TypedDict, total=False):\n" +"... x: int\n" +"... y: int\n" +"...\n" +">>> class Point3D(Point2D):\n" +"... z: int\n" +"...\n" +">>> Point3D.__required_keys__ == frozenset({'z'})\n" +"True\n" +">>> Point3D.__optional_keys__ == frozenset({'x', 'y'})\n" +"True" #: ../Doc/library/typing.rst:2645 msgid "" @@ -4435,22 +5219,35 @@ msgid "" "``__optional_keys__`` rely on may not work properly, and the values of the " "attributes may be incorrect." msgstr "" +"Si se utiliza ``from __future__ import annotations`` o si las anotaciones se " +"proporcionan como cadenas, las anotaciones no se evalúan cuando se define " +"``TypedDict``. Por lo tanto, la introspección en tiempo de ejecución de la " +"que dependen ``__required_keys__`` y ``__optional_keys__`` puede no " +"funcionar correctamente y los valores de los atributos pueden ser " +"incorrectos." #: ../Doc/library/typing.rst:2651 msgid "Support for :data:`ReadOnly` is reflected in the following attributes:" msgstr "" +"La compatibilidad con :data:`ReadOnly` se refleja en los siguientes " +"atributos:" #: ../Doc/library/typing.rst:2655 msgid "" "A :class:`frozenset` containing the names of all read-only keys. Keys are " "read-only if they carry the :data:`ReadOnly` qualifier." msgstr "" +"Un :class:`frozenset` que contiene los nombres de todas las claves de solo " +"lectura. Las claves son de solo lectura si llevan el calificador :data:" +"`ReadOnly`." #: ../Doc/library/typing.rst:2662 msgid "" "A :class:`frozenset` containing the names of all mutable keys. Keys are " "mutable if they do not carry the :data:`ReadOnly` qualifier." msgstr "" +"Un :class:`frozenset` que contiene los nombres de todas las claves mutables. " +"Las claves son mutables si no llevan el calificador :data:`ReadOnly`." #: ../Doc/library/typing.rst:2667 msgid "" @@ -4472,15 +5269,16 @@ msgid "Added support for generic ``TypedDict``\\ s." msgstr "Se agrega soporte para ``TypedDict`` genéricos." #: ../Doc/library/typing.rst:2678 -#, fuzzy msgid "" "Removed support for the keyword-argument method of creating ``TypedDict``\\ " "s." -msgstr "Se agrega soporte para ``TypedDict`` genéricos." +msgstr "" +"Se eliminó la compatibilidad con el método de argumento de palabra clave " +"para crear ``TypedDict``\\ s." #: ../Doc/library/typing.rst:2681 msgid "Support for the :data:`ReadOnly` qualifier was added." -msgstr "" +msgstr "Se agregó soporte para el calificador :data:`ReadOnly`." #: ../Doc/library/typing.rst:2684 msgid "" @@ -4491,6 +5289,12 @@ msgid "" "Python 3.15. To create a TypedDict class with 0 fields, use ``class " "TD(TypedDict): pass`` or ``TD = TypedDict(\"TD\", {})``." msgstr "" +"Al utilizar la sintaxis funcional para crear una clase TypedDict, no se " +"permite pasar un valor al parámetro 'campos' (``TD = TypedDict(\"TD\")``). " +"También se permite pasar ``None`` al parámetro 'campos' (``TD = " +"TypedDict(\"TD\", None)``). Ambos métodos no estarán permitidos en Python " +"3.15. Para crear una clase TypedDict con 0 campos, utilice ``class " +"TD(TypedDict): pass`` o ``TD = TypedDict(\"TD\", {})``." #: ../Doc/library/typing.rst:2693 msgid "Protocols" @@ -4603,6 +5407,9 @@ msgid "" " assert_type(name, str) # OK, inferred type of `name` is `str`\n" " assert_type(name, int) # type checker error" msgstr "" +"def greet(name: str) -> None:\n" +" assert_type(name, str) # OK, tipo inferido de `name` es `str`\n" +" assert_type(name, int) # error del verificador de tipos" #: ../Doc/library/typing.rst:2768 msgid "" @@ -4622,6 +5429,13 @@ msgid "" " # Test whether the type checker correctly understands our function\n" " assert_type(arg, int)" msgstr "" +"def complex_function(arg: object):\n" +" # Haz alguna lógica compleja de reducción de tipo,\n" +" # despues de la cual esperamos que el tipo inferido sea `int`\n" +" ...\n" +" # Probar si el verificador de tipos entiende correctamente nuestra " +"función\n" +" assert_type(arg, int)" #: ../Doc/library/typing.rst:2782 msgid "" @@ -4645,6 +5459,14 @@ msgid "" " case _ as unreachable:\n" " assert_never(unreachable)" msgstr "" +"def int_or_str(arg: int | str) -> None:\n" +" match arg:\n" +" case int():\n" +" print(\"It's an int\")\n" +" case str():\n" +" print(\"It's a str\")\n" +" case _ as unreachable:\n" +" assert_never(unreachable)" #: ../Doc/library/typing.rst:2795 msgid "" @@ -4678,37 +5500,37 @@ msgid "At runtime, this throws an exception when called." msgstr "En tiempo de ejecución, ésto lanza una excepción cuando es llamado." #: ../Doc/library/typing.rst:2811 -#, fuzzy msgid "" "`Unreachable Code and Exhaustiveness Checking `__ has more information about " "exhaustiveness checking with static typing." msgstr "" "`Unreachable Code and Exhaustiveness Checking `__ contiene más información acerca de la " -"verificación de exhaustividad con tipado estático." +"en/latest/guides/unreachable.html>`__ tiene más información sobre la " +"comprobación de exhaustividad con tipado estático." #: ../Doc/library/typing.rst:2819 -#, fuzzy msgid "Ask a static type checker to reveal the inferred type of an expression." msgstr "" -"Solicitar a un validador de tipos que confirme que *val* tiene *typ* por " -"tipo inferido." +"Pídale a un verificador de tipos estáticos que revele el tipo inferido de " +"una expresión." #: ../Doc/library/typing.rst:2821 -#, fuzzy msgid "" "When a static type checker encounters a call to this function, it emits a " "diagnostic with the inferred type of the argument. For example::" msgstr "" -"Cuando un validador estático de tipos se encuentra con una invocación a esta " -"función, emite un diagnostico con el tipo del argumento. Por ejemplo::" +"Cuando un verificador de tipos estáticos encuentra una llamada a esta " +"función, emite un diagnóstico con el tipo inferido del argumento. Por " +"ejemplo:" #: ../Doc/library/typing.rst:2824 msgid "" "x: int = 1\n" "reveal_type(x) # Revealed type is \"builtins.int\"" msgstr "" +"x: int = 1\n" +"reveal_type(x) # Tipo revelado es \"builtins.int\"" #: ../Doc/library/typing.rst:2827 msgid "" @@ -4719,39 +5541,44 @@ msgstr "" "tipos maneja una pieza particular de código." #: ../Doc/library/typing.rst:2830 -#, fuzzy msgid "" "At runtime, this function prints the runtime type of its argument to :data:" "`sys.stderr` and returns the argument unchanged (allowing the call to be " "used within an expression)::" msgstr "" -"En tiempo de ejecución, esta función imprime al *stderr* el tipo en tiempo " -"de ejecución de su argumento y lo retorna in cambios::" +"En tiempo de ejecución, esta función imprime el tipo de tiempo de ejecución " +"de su argumento en :data:`sys.stderr` y devuelve el argumento sin cambios " +"(lo que permite que la llamada se use dentro de una expresión):" #: ../Doc/library/typing.rst:2834 msgid "" "x = reveal_type(1) # prints \"Runtime type is int\"\n" "print(x) # prints \"1\"" msgstr "" +"x = reveal_type(1) # imprime \"Runtime type is int\"\n" +"print(x) # prints \"1\"" #: ../Doc/library/typing.rst:2837 msgid "" "Note that the runtime type may be different from (more or less specific " "than) the type statically inferred by a type checker." msgstr "" +"Tenga en cuenta que el tipo de tiempo de ejecución puede ser diferente (más " +"o menos específico) del tipo inferido estáticamente por un verificador de " +"tipos." #: ../Doc/library/typing.rst:2840 -#, fuzzy msgid "" "Most type checkers support ``reveal_type()`` anywhere, even if the name is " "not imported from ``typing``. Importing the name from ``typing``, however, " "allows your code to run without runtime errors and communicates intent more " "clearly." msgstr "" -"La mayoría de los validadores de tipos soportan ``reveal_type()`` en " -"cualquier lugar, incluso si el nombre no ha sido importado desde ``typing``. " -"Importar el nombre desde ``typing`` permite que el código corra sin errores " -"en tiempo de ejecución y comunica la intención de forma más clara." +"La mayoría de los verificadores de tipos admiten ``reveal_type()`` en " +"cualquier lugar, incluso si el nombre no se importa desde ``typing``. Sin " +"embargo, importar el nombre desde ``typing`` permite que el código se " +"ejecute sin errores de tiempo de ejecución y comunica la intención con mayor " +"claridad." #: ../Doc/library/typing.rst:2851 msgid "" @@ -4792,6 +5619,15 @@ msgid "" " id: int\n" " name: str" msgstr "" +"@dataclass_transform()\n" +"def create_model[T](cls: type[T]) -> type[T]:\n" +" ...\n" +" return cls\n" +"\n" +"@create_model\n" +"class CustomerModel:\n" +" id: int\n" +" name: str" #: ../Doc/library/typing.rst:2875 msgid "On a base class::" @@ -4806,6 +5642,12 @@ msgid "" " id: int\n" " name: str" msgstr "" +"@dataclass_transform()\n" +"class ModelBase: ...\n" +"\n" +"class CustomerModel(ModelBase):\n" +" id: int\n" +" name: str" #: ../Doc/library/typing.rst:2884 msgid "On a metaclass::" @@ -4822,6 +5664,14 @@ msgid "" " id: int\n" " name: str" msgstr "" +"@dataclass_transform()\n" +"class ModelMeta(type): ...\n" +"\n" +"class ModelBase(metaclass=ModelMeta): ...\n" +"\n" +"class CustomerModel(ModelBase):\n" +" id: int\n" +" name: str" #: ../Doc/library/typing.rst:2895 msgid "" @@ -5243,6 +6093,9 @@ msgid "" "No type checker ever added support for ``@no_type_check_decorator``. It is " "therefore deprecated, and will be removed in Python 3.15." msgstr "" +"Ningún verificador de tipos agregó compatibilidad con " +"``@no_type_check_decorator``. Por lo tanto, está obsoleto y se eliminará en " +"Python 3.15." #: ../Doc/library/typing.rst:3120 msgid "" @@ -5354,6 +6207,8 @@ msgid "" "This is often the same as ``obj.__annotations__``, but this function makes " "the following changes to the annotations dictionary:" msgstr "" +"A menudo es lo mismo que ``obj.__annotations__``, pero esta función realiza " +"los siguientes cambios en el diccionario de anotaciones:" #: ../Doc/library/typing.rst:3188 msgid "" @@ -5363,16 +6218,23 @@ msgid "" "*globalns* or *localns* is not given, appropriate namespace dictionaries are " "inferred from *obj*." msgstr "" +"Las referencias futuras codificadas como literales de cadena u objetos :" +"class:`ForwardRef` se manejan evaluándolas en el espacio de nombres " +"*globalns*, *localns* y (cuando corresponda) el espacio de nombre :ref:`type " +"parameter ` *obj*. Si no se proporciona *globalns* o *localns*, " +"los diccionarios de espacios de nombres apropiados se infieren de *obj*." #: ../Doc/library/typing.rst:3193 msgid "``None`` is replaced with :class:`types.NoneType`." -msgstr "" +msgstr "``None`` se reemplaza por :class:`types.NoneType`." #: ../Doc/library/typing.rst:3194 msgid "" "If :func:`@no_type_check ` has been applied to *obj*, an " "empty dictionary is returned." msgstr "" +"Si se ha aplicado :func:`@no_type_check ` a *obj*, se " +"devuelve un diccionario vacío." #: ../Doc/library/typing.rst:3196 msgid "" @@ -5383,23 +6245,31 @@ msgid "" "earlier in the :term:`method resolution order` always take precedence over " "annotations on classes appearing later in the method resolution order." msgstr "" +"Si *obj* es una clase ``C``, la función devuelve un diccionario que fusiona " +"las anotaciones de las clases base de ``C`` con las de ``C`` directamente. " +"Esto se hace recorriendo :attr:`C.__mro__ ` y combinando " +"iterativamente los diccionarios ``__annotations__``. Las anotaciones sobre " +"las clases que aparecen antes en :term:`method resolution order` siempre " +"tienen prioridad sobre las anotaciones sobre las clases que aparecen después " +"en el orden de resolución del método." #: ../Doc/library/typing.rst:3203 -#, fuzzy msgid "" "The function recursively replaces all occurrences of ``Annotated[T, ...]`` " "with ``T``, unless *include_extras* is set to ``True`` (see :class:" "`Annotated` for more information)." msgstr "" -"La función reemplaza recursivamente todos los ``Annotated[T, ...]`` con " -"``T``, a menos que ``include_extras`` esté configurado como ``True`` " -"(consulte :class:`Annotated` para obtener más información). Por ejemplo:" +"La función reemplaza recursivamente todas las apariciones de " +"``Annotated[T, ...]`` con ``T``, a menos que *include_extras* se configure " +"en ``True`` (consulte :class:`Annotated` para obtener más información)." #: ../Doc/library/typing.rst:3207 msgid "" "See also :func:`inspect.get_annotations`, a lower-level function that " "returns annotations more directly." msgstr "" +"Consulte también :func:`inspect.get_annotations`, una función de nivel " +"inferior que devuelve anotaciones de forma más directa." #: ../Doc/library/typing.rst:3212 msgid "" @@ -5409,6 +6279,11 @@ msgid "" "aliases ` that include forward references, or with names " "imported under :data:`if TYPE_CHECKING `." msgstr "" +"Si alguna referencia hacia adelante en las anotaciones de *obj* no se puede " +"resolver o no es código Python válido, esta función generará una excepción " +"como :exc:`NameError`. Por ejemplo, esto puede suceder con :ref:`type " +"aliases ` importado que incluye referencias hacia adelante o " +"con nombres importados bajo :data:`if TYPE_CHECKING `." #: ../Doc/library/typing.rst:3218 msgid "" @@ -5462,6 +6337,13 @@ msgid "" "assert get_origin(P.args) is P\n" "assert get_origin(P.kwargs) is P" msgstr "" +"assert get_origin(str) is None\n" +"assert get_origin(Dict[str, int]) is dict\n" +"assert get_origin(Union[int, str]) is Union\n" +"assert get_origin(Annotated[str, \"metadata\"]) is Annotated\n" +"P = ParamSpec('P')\n" +"assert get_origin(P.args) is P\n" +"assert get_origin(P.kwargs) is P" #: ../Doc/library/typing.rst:3254 msgid "" @@ -5489,10 +6371,13 @@ msgid "" "assert get_args(Dict[int, str]) == (int, str)\n" "assert get_args(Union[int, str]) == (int, str)" msgstr "" +"assert get_args(int) == ()\n" +"assert get_args(Dict[int, str]) == (int, str)\n" +"assert get_args(Union[int, str]) == (int, str)" #: ../Doc/library/typing.rst:3274 msgid "Return the set of members defined in a :class:`Protocol`." -msgstr "" +msgstr "Devuelve el conjunto de miembros definidos en un :class:`Protocol`." #: ../Doc/library/typing.rst:3276 msgid "" @@ -5503,13 +6388,18 @@ msgid "" ">>> get_protocol_members(P) == frozenset({'a', 'b'})\n" "True" msgstr "" +">>> from typing import Protocol, get_protocol_members\n" +">>> class P(Protocol):\n" +"... def a(self) -> str: ...\n" +"... b: int\n" +">>> get_protocol_members(P) == frozenset({'a', 'b'})\n" +"True" #: ../Doc/library/typing.rst:3285 msgid "Raise :exc:`TypeError` for arguments that are not Protocols." -msgstr "" +msgstr "Genera :exc:`TypeError` para argumentos que no sean protocolos." #: ../Doc/library/typing.rst:3291 -#, fuzzy msgid "Determine if a type is a :class:`Protocol`." msgstr "Compruebe si un tipo es :class:`TypedDict`." @@ -5522,6 +6412,12 @@ msgid "" "is_protocol(P) # => True\n" "is_protocol(int) # => False" msgstr "" +"class P(Protocol):\n" +" def a(self) -> str: ...\n" +" b: int\n" +"\n" +"is_protocol(P) # => True\n" +"is_protocol(int) # => False" #: ../Doc/library/typing.rst:3306 msgid "Check if a type is a :class:`TypedDict`." @@ -5540,6 +6436,16 @@ msgid "" "# not a typed dict itself\n" "assert not is_typeddict(TypedDict)" msgstr "" +"class Film(TypedDict):\n" +" title: str\n" +" year: int\n" +"\n" +"assert is_typeddict(Film)\n" +"assert not is_typeddict(list | str)\n" +"\n" +"# TypedDict es una fábrica para crear diccionarios tipados,\n" +"# no un diccionario tipado en si mismo\n" +"assert not is_typeddict(TypedDict)" #: ../Doc/library/typing.rst:3327 msgid "" @@ -5573,6 +6479,8 @@ msgid "" "A sentinel object used to indicate that a type parameter has no default " "value. For example:" msgstr "" +"Un objeto centinela que se utiliza para indicar que un parámetro de tipo no " +"tiene un valor predeterminado. Por ejemplo:" #: ../Doc/library/typing.rst:3345 msgid "" @@ -5583,6 +6491,12 @@ msgid "" ">>> S.__default__ is None\n" "True" msgstr "" +">>> T = TypeVar(\"T\")\n" +">>> T.__default__ is typing.NoDefault\n" +"True\n" +">>> S = TypeVar(\"S\", default=None)\n" +">>> S.__default__ is None\n" +"True" #: ../Doc/library/typing.rst:3357 msgid "Constant" @@ -5604,6 +6518,11 @@ msgid "" "def fun(arg: 'expensive_mod.SomeType') -> None:\n" " local_var: expensive_mod.AnotherType = other_fun()" msgstr "" +"if TYPE_CHECKING:\n" +" import expensive_mod\n" +"\n" +"def fun(arg: 'expensive_mod.SomeType') -> None:\n" +" local_var: expensive_mod.AnotherType = other_fun()" #: ../Doc/library/typing.rst:3372 msgid "" @@ -5691,15 +6610,14 @@ msgid "Deprecated alias to :class:`dict`." msgstr "Alias obsoleto de :class:`dict`." #: ../Doc/library/typing.rst:3422 -#, fuzzy msgid "" "Note that to annotate arguments, it is preferred to use an abstract " "collection type such as :class:`~collections.abc.Mapping` rather than to " "use :class:`dict` or :class:`!typing.Dict`." msgstr "" -"Tenga en cuenta que para anotar argumentos, es preferible utilizar un tipo " -"de colección abstracto como :class:`Mapping` en lugar de utilizar :class:" -"`dict` o :class:`!typing.Dict`." +"Tenga en cuenta que para anotar argumentos, se prefiere utilizar un tipo de " +"colección abstracto como :class:`~collections.abc.Mapping` en lugar de " +"utilizar :class:`dict` o :class:`!typing.Dict`." #: ../Doc/library/typing.rst:3426 msgid "" @@ -5714,16 +6632,16 @@ msgid "Deprecated alias to :class:`list`." msgstr "Alias obsoleto de :class:`list`." #: ../Doc/library/typing.rst:3434 -#, fuzzy msgid "" "Note that to annotate arguments, it is preferred to use an abstract " "collection type such as :class:`~collections.abc.Sequence` or :class:" "`~collections.abc.Iterable` rather than to use :class:`list` or :class:`!" "typing.List`." msgstr "" -"Tenga en cuenta que para anotar argumentos, es preferible utilizar un tipo " -"de colección abstracto como :class:`Sequence` o :class:`Iterable` en lugar " -"de utilizar :class:`list` o :class:`!typing.List`." +"Tenga en cuenta que para anotar argumentos, se prefiere utilizar un tipo de " +"colección abstracto como :class:`~collections.abc.Sequence` o :class:" +"`~collections.abc.Iterable` en lugar de utilizar :class:`list` o :class:`!" +"typing.List`." #: ../Doc/library/typing.rst:3439 msgid "" @@ -5738,15 +6656,14 @@ msgid "Deprecated alias to :class:`builtins.set `." msgstr "Alias obsoleto de :class:`builtins.set `." #: ../Doc/library/typing.rst:3447 -#, fuzzy msgid "" "Note that to annotate arguments, it is preferred to use an abstract " "collection type such as :class:`collections.abc.Set` rather than to use :" "class:`set` or :class:`typing.Set`." msgstr "" -"Tenga en cuenta que para anotar argumentos, es preferible utilizar un tipo " -"de colección abstracto como :class:`AbstractSet` en lugar de utilizar :class:" -"`set` o :class:`!typing.Set`." +"Tenga en cuenta que para anotar argumentos, se prefiere utilizar un tipo de " +"colección abstracto como :class:`collections.abc.Set` en lugar de utilizar :" +"class:`set` o :class:`typing.Set`." #: ../Doc/library/typing.rst:3451 msgid "" @@ -5929,6 +6846,8 @@ msgid "" "def add_unicode_checkmark(text: Text) -> Text:\n" " return text + u' \\u2713'" msgstr "" +"def add_unicode_checkmark(text: Text) -> Text:\n" +" return text + u' \\u2713'" #: ../Doc/library/typing.rst:3579 msgid "" @@ -6114,14 +7033,13 @@ msgid "Deprecated alias to :class:`collections.abc.Coroutine`." msgstr "Alias obsoleto de :class:`collections.abc.Coroutine`." #: ../Doc/library/typing.rst:3708 -#, fuzzy msgid "" "See :ref:`annotating-generators-and-coroutines` for details on using :class:" "`collections.abc.Coroutine` and ``typing.Coroutine`` in type annotations." msgstr "" -"Vea :ref:`annotating-callables` para información detallada de cómo usar :" -"class:`collections.abc.Callable` y ``typing.Callable`` en anotaciones de " -"tipo." +"Consulte :ref:`annotating-generators-and-coroutines` para obtener detalles " +"sobre el uso de :class:`collections.abc.Coroutine` y ``typing.Coroutine`` en " +"anotaciones de tipo." #: ../Doc/library/typing.rst:3714 msgid "" @@ -6136,15 +7054,14 @@ msgid "Deprecated alias to :class:`collections.abc.AsyncGenerator`." msgstr "Alias obsoleto de :class:`collections.abc.AsyncGenerator`." #: ../Doc/library/typing.rst:3722 -#, fuzzy msgid "" "See :ref:`annotating-generators-and-coroutines` for details on using :class:" "`collections.abc.AsyncGenerator` and ``typing.AsyncGenerator`` in type " "annotations." msgstr "" -"Vea :ref:`annotating-callables` para información detallada de cómo usar :" -"class:`collections.abc.Callable` y ``typing.Callable`` en anotaciones de " -"tipo." +"Consulte :ref:`annotating-generators-and-coroutines` para obtener detalles " +"sobre el uso de :class:`collections.abc.AsyncGenerator` y ``typing." +"AsyncGenerator`` en anotaciones de tipo." #: ../Doc/library/typing.rst:3728 msgid "" @@ -6156,7 +7073,7 @@ msgstr "" #: ../Doc/library/typing.rst:3733 msgid "The ``SendType`` parameter now has a default." -msgstr "" +msgstr "El parámetro ``SendType`` ahora tiene un valor predeterminado." #: ../Doc/library/typing.rst:3738 msgid "Deprecated alias to :class:`collections.abc.AsyncIterable`." @@ -6248,14 +7165,13 @@ msgid "Deprecated alias to :class:`collections.abc.Generator`." msgstr "Alias obsoleto de :class:`collections.abc.Generator`." #: ../Doc/library/typing.rst:3806 -#, fuzzy msgid "" "See :ref:`annotating-generators-and-coroutines` for details on using :class:" "`collections.abc.Generator` and ``typing.Generator`` in type annotations." msgstr "" -"Vea :ref:`annotating-callables` para información detallada de cómo usar :" -"class:`collections.abc.Callable` y ``typing.Callable`` en anotaciones de " -"tipo." +"Consulte :ref:`annotating-generators-and-coroutines` para obtener detalles " +"sobre el uso de :class:`collections.abc.Generator` y ``typing.Generator`` en " +"anotaciones de tipo." #: ../Doc/library/typing.rst:3810 msgid "" @@ -6267,7 +7183,7 @@ msgstr "" #: ../Doc/library/typing.rst:3814 msgid "Default values for the send and return types were added." -msgstr "" +msgstr "Valores por defecto para los tipos send y return fueron agregados." #: ../Doc/library/typing.rst:3819 msgid "Deprecated alias to :class:`collections.abc.Hashable`." @@ -6312,6 +7228,10 @@ msgid "" "``ExitT_co``, which defaults to ``bool | None``, represents the type " "returned by the :meth:`~object.__exit__` method." msgstr "" +"El primer parámetro de tipo, ``T_co``, representa el tipo devuelto por el " +"método :meth:`~object.__enter__`. El segundo parámetro de tipo opcional, " +"``ExitT_co``, cuyo valor predeterminado es ``bool | None``, representa el " +"tipo devuelto por el método :meth:`~object.__exit__`." #: ../Doc/library/typing.rst:3855 msgid "" @@ -6323,7 +7243,7 @@ msgstr "" #: ../Doc/library/typing.rst:3860 msgid "Added the optional second type parameter, ``ExitT_co``." -msgstr "" +msgstr "Se agregó el segundo parámetro de tipo opcional, ``ExitT_co``." #: ../Doc/library/typing.rst:3865 msgid "Deprecated alias to :class:`contextlib.AbstractAsyncContextManager`." @@ -6336,6 +7256,10 @@ msgid "" "``AExitT_co``, which defaults to ``bool | None``, represents the type " "returned by the :meth:`~object.__aexit__` method." msgstr "" +"El primer parámetro de tipo, ``T_co``, representa el tipo devuelto por el " +"método :meth:`~object.__aenter__`. El segundo parámetro de tipo opcional, " +"``AExitT_co``, cuyo valor predeterminado es ``bool | None``, representa el " +"tipo devuelto por el método :meth:`~object.__aexit__`." #: ../Doc/library/typing.rst:3874 msgid "" @@ -6347,7 +7271,7 @@ msgstr "" #: ../Doc/library/typing.rst:3879 msgid "Added the optional second type parameter, ``AExitT_co``." -msgstr "" +msgstr "Se agregó el segundo parámetro de tipo opcional, ``AExitT_co``." #: ../Doc/library/typing.rst:3883 msgid "Deprecation Timeline of Major Features" @@ -6448,33 +7372,28 @@ msgstr ":pep:`695`" #: ../Doc/library/typing.rst:3916 msgid ":func:`@typing.no_type_check_decorator `" -msgstr "" +msgstr ":func:`@typing.no_type_check_decorator `" #: ../Doc/library/typing.rst:3917 ../Doc/library/typing.rst:3921 msgid "3.13" msgstr "3.13" #: ../Doc/library/typing.rst:3918 -#, fuzzy msgid "3.15" -msgstr "3.14" +msgstr "3.15" #: ../Doc/library/typing.rst:3919 -#, fuzzy msgid ":gh:`106309`" -msgstr ":gh:`94309`" +msgstr ":gh:`106309`" #: ../Doc/library/typing.rst:3920 -#, fuzzy msgid ":data:`typing.AnyStr`" -msgstr ":data:`typing.Text`" +msgstr ":data:`typing.AnyStr`" #: ../Doc/library/typing.rst:3922 -#, fuzzy msgid "3.18" -msgstr "3.8" +msgstr "3.18" #: ../Doc/library/typing.rst:3923 -#, fuzzy msgid ":gh:`105578`" -msgstr ":gh:`91896`" +msgstr ":gh:`105578`"