Skip to content

Commit ab71acd

Browse files
typing docs: Move some classes out of the "Generics" section (#104707)
- AnyStr can be used in type annotations, contrary to the section header - Unpack can also be used in annotations, and its use is not restricted to generics. It makes more sense with other building blocks like Required. - Protocol is not necessarily generic. Also fix the indentation for two notes associated with Concatenate. Split off from #104642, but I think this change is independently an improvement.
1 parent b9fcfa6 commit ab71acd

File tree

1 file changed

+146
-146
lines changed

1 file changed

+146
-146
lines changed

Doc/library/typing.rst

+146-146
Original file line numberDiff line numberDiff line change
@@ -616,6 +616,21 @@ These can be used as types in annotations and do not support ``[]``.
616616
avoiding type checker errors with classes that can duck type anywhere or
617617
are highly dynamic.
618618

619+
.. data:: AnyStr
620+
621+
``AnyStr`` is a :ref:`constrained type variable <typing-constrained-typevar>` defined as
622+
``AnyStr = TypeVar('AnyStr', str, bytes)``.
623+
624+
It is meant to be used for functions that may accept any kind of string
625+
without allowing different kinds of strings to mix. For example::
626+
627+
def concat(a: AnyStr, b: AnyStr) -> AnyStr:
628+
return a + b
629+
630+
concat(u"foo", u"bar") # Ok, output has type 'unicode'
631+
concat(b"foo", b"bar") # Ok, output has type 'bytes'
632+
concat(u"foo", b"bar") # Error, cannot mix unicode and bytes
633+
619634
.. data:: LiteralString
620635

621636
Special type that includes only literal strings. A string
@@ -917,13 +932,13 @@ These can be used as types in annotations using ``[]``, each having a unique syn
917932
# We don't need to pass in the lock ourselves thanks to the decorator.
918933
sum_threadsafe([1.1, 2.2, 3.3])
919934

920-
.. versionadded:: 3.10
935+
.. versionadded:: 3.10
921936

922-
.. seealso::
937+
.. seealso::
923938

924-
* :pep:`612` -- Parameter Specification Variables (the PEP which introduced
925-
``ParamSpec`` and ``Concatenate``).
926-
* :class:`ParamSpec` and :class:`Callable`.
939+
* :pep:`612` -- Parameter Specification Variables (the PEP which introduced
940+
``ParamSpec`` and ``Concatenate``).
941+
* :class:`ParamSpec` and :class:`Callable`.
927942

928943

929944
.. class:: Type(Generic[CT_co])
@@ -1208,6 +1223,49 @@ These can be used as types in annotations using ``[]``, each having a unique syn
12081223
.. versionadded:: 3.10
12091224

12101225

1226+
.. data:: Unpack
1227+
1228+
A typing operator that conceptually marks an object as having been
1229+
unpacked. For example, using the unpack operator ``*`` on a
1230+
:class:`type variable tuple <TypeVarTuple>` is equivalent to using ``Unpack``
1231+
to mark the type variable tuple as having been unpacked::
1232+
1233+
Ts = TypeVarTuple('Ts')
1234+
tup: tuple[*Ts]
1235+
# Effectively does:
1236+
tup: tuple[Unpack[Ts]]
1237+
1238+
In fact, ``Unpack`` can be used interchangeably with ``*`` in the context
1239+
of :class:`typing.TypeVarTuple <TypeVarTuple>` and
1240+
:class:`builtins.tuple <tuple>` types. You might see ``Unpack`` being used
1241+
explicitly in older versions of Python, where ``*`` couldn't be used in
1242+
certain places::
1243+
1244+
# In older versions of Python, TypeVarTuple and Unpack
1245+
# are located in the `typing_extensions` backports package.
1246+
from typing_extensions import TypeVarTuple, Unpack
1247+
1248+
Ts = TypeVarTuple('Ts')
1249+
tup: tuple[*Ts] # Syntax error on Python <= 3.10!
1250+
tup: tuple[Unpack[Ts]] # Semantically equivalent, and backwards-compatible
1251+
1252+
``Unpack`` can also be used along with :class:`typing.TypedDict` for typing
1253+
``**kwargs`` in a function signature::
1254+
1255+
from typing import TypedDict, Unpack
1256+
1257+
class Movie(TypedDict):
1258+
name: str
1259+
year: int
1260+
1261+
# This function expects two keyword arguments - `name` of type `str`
1262+
# and `year` of type `int`.
1263+
def foo(**kwargs: Unpack[Movie]): ...
1264+
1265+
See :pep:`692` for more details on using ``Unpack`` for ``**kwargs`` typing.
1266+
1267+
.. versionadded:: 3.11
1268+
12111269
Building generic types
12121270
""""""""""""""""""""""
12131271

@@ -1409,49 +1467,6 @@ These are not used in annotations. They are building blocks for creating generic
14091467

14101468
.. versionadded:: 3.11
14111469

1412-
.. data:: Unpack
1413-
1414-
A typing operator that conceptually marks an object as having been
1415-
unpacked. For example, using the unpack operator ``*`` on a
1416-
:class:`type variable tuple <TypeVarTuple>` is equivalent to using ``Unpack``
1417-
to mark the type variable tuple as having been unpacked::
1418-
1419-
Ts = TypeVarTuple('Ts')
1420-
tup: tuple[*Ts]
1421-
# Effectively does:
1422-
tup: tuple[Unpack[Ts]]
1423-
1424-
In fact, ``Unpack`` can be used interchangeably with ``*`` in the context
1425-
of :class:`typing.TypeVarTuple <TypeVarTuple>` and
1426-
:class:`builtins.tuple <tuple>` types. You might see ``Unpack`` being used
1427-
explicitly in older versions of Python, where ``*`` couldn't be used in
1428-
certain places::
1429-
1430-
# In older versions of Python, TypeVarTuple and Unpack
1431-
# are located in the `typing_extensions` backports package.
1432-
from typing_extensions import TypeVarTuple, Unpack
1433-
1434-
Ts = TypeVarTuple('Ts')
1435-
tup: tuple[*Ts] # Syntax error on Python <= 3.10!
1436-
tup: tuple[Unpack[Ts]] # Semantically equivalent, and backwards-compatible
1437-
1438-
``Unpack`` can also be used along with :class:`typing.TypedDict` for typing
1439-
``**kwargs`` in a function signature::
1440-
1441-
from typing import TypedDict, Unpack
1442-
1443-
class Movie(TypedDict):
1444-
name: str
1445-
year: int
1446-
1447-
# This function expects two keyword arguments - `name` of type `str`
1448-
# and `year` of type `int`.
1449-
def foo(**kwargs: Unpack[Movie]): ...
1450-
1451-
See :pep:`692` for more details on using ``Unpack`` for ``**kwargs`` typing.
1452-
1453-
.. versionadded:: 3.11
1454-
14551470
.. class:: ParamSpec(name, *, bound=None, covariant=False, contravariant=False)
14561471

14571472
Parameter specification variable. A specialized version of
@@ -1550,20 +1565,93 @@ These are not used in annotations. They are building blocks for creating generic
15501565
.. versionadded:: 3.10
15511566

15521567

1553-
.. data:: AnyStr
1568+
Other special directives
1569+
""""""""""""""""""""""""
15541570

1555-
``AnyStr`` is a :ref:`constrained type variable <typing-constrained-typevar>` defined as
1556-
``AnyStr = TypeVar('AnyStr', str, bytes)``.
1571+
These are not used in annotations. They are building blocks for declaring types.
15571572

1558-
It is meant to be used for functions that may accept any kind of string
1559-
without allowing different kinds of strings to mix. For example::
1573+
.. class:: NamedTuple
15601574

1561-
def concat(a: AnyStr, b: AnyStr) -> AnyStr:
1562-
return a + b
1575+
Typed version of :func:`collections.namedtuple`.
15631576

1564-
concat(u"foo", u"bar") # Ok, output has type 'unicode'
1565-
concat(b"foo", b"bar") # Ok, output has type 'bytes'
1566-
concat(u"foo", b"bar") # Error, cannot mix unicode and bytes
1577+
Usage::
1578+
1579+
class Employee(NamedTuple):
1580+
name: str
1581+
id: int
1582+
1583+
This is equivalent to::
1584+
1585+
Employee = collections.namedtuple('Employee', ['name', 'id'])
1586+
1587+
To give a field a default value, you can assign to it in the class body::
1588+
1589+
class Employee(NamedTuple):
1590+
name: str
1591+
id: int = 3
1592+
1593+
employee = Employee('Guido')
1594+
assert employee.id == 3
1595+
1596+
Fields with a default value must come after any fields without a default.
1597+
1598+
The resulting class has an extra attribute ``__annotations__`` giving a
1599+
dict that maps the field names to the field types. (The field names are in
1600+
the ``_fields`` attribute and the default values are in the
1601+
``_field_defaults`` attribute, both of which are part of the :func:`~collections.namedtuple`
1602+
API.)
1603+
1604+
``NamedTuple`` subclasses can also have docstrings and methods::
1605+
1606+
class Employee(NamedTuple):
1607+
"""Represents an employee."""
1608+
name: str
1609+
id: int = 3
1610+
1611+
def __repr__(self) -> str:
1612+
return f'<Employee {self.name}, id={self.id}>'
1613+
1614+
``NamedTuple`` subclasses can be generic::
1615+
1616+
class Group(NamedTuple, Generic[T]):
1617+
key: T
1618+
group: list[T]
1619+
1620+
Backward-compatible usage::
1621+
1622+
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1623+
1624+
.. versionchanged:: 3.6
1625+
Added support for :pep:`526` variable annotation syntax.
1626+
1627+
.. versionchanged:: 3.6.1
1628+
Added support for default values, methods, and docstrings.
1629+
1630+
.. versionchanged:: 3.8
1631+
The ``_field_types`` and ``__annotations__`` attributes are
1632+
now regular dictionaries instead of instances of ``OrderedDict``.
1633+
1634+
.. versionchanged:: 3.9
1635+
Removed the ``_field_types`` attribute in favor of the more
1636+
standard ``__annotations__`` attribute which has the same information.
1637+
1638+
.. versionchanged:: 3.11
1639+
Added support for generic namedtuples.
1640+
1641+
.. class:: NewType(name, tp)
1642+
1643+
A helper class to indicate a distinct type to a typechecker,
1644+
see :ref:`distinct`. At runtime it returns an object that returns
1645+
its argument when called.
1646+
Usage::
1647+
1648+
UserId = NewType('UserId', int)
1649+
first_user = UserId(1)
1650+
1651+
.. versionadded:: 3.5.2
1652+
1653+
.. versionchanged:: 3.10
1654+
``NewType`` is now a class rather than a function.
15671655

15681656
.. class:: Protocol(Generic)
15691657

@@ -1659,94 +1747,6 @@ These are not used in annotations. They are building blocks for creating generic
16591747
for more details.
16601748

16611749

1662-
Other special directives
1663-
""""""""""""""""""""""""
1664-
1665-
These are not used in annotations. They are building blocks for declaring types.
1666-
1667-
.. class:: NamedTuple
1668-
1669-
Typed version of :func:`collections.namedtuple`.
1670-
1671-
Usage::
1672-
1673-
class Employee(NamedTuple):
1674-
name: str
1675-
id: int
1676-
1677-
This is equivalent to::
1678-
1679-
Employee = collections.namedtuple('Employee', ['name', 'id'])
1680-
1681-
To give a field a default value, you can assign to it in the class body::
1682-
1683-
class Employee(NamedTuple):
1684-
name: str
1685-
id: int = 3
1686-
1687-
employee = Employee('Guido')
1688-
assert employee.id == 3
1689-
1690-
Fields with a default value must come after any fields without a default.
1691-
1692-
The resulting class has an extra attribute ``__annotations__`` giving a
1693-
dict that maps the field names to the field types. (The field names are in
1694-
the ``_fields`` attribute and the default values are in the
1695-
``_field_defaults`` attribute, both of which are part of the :func:`~collections.namedtuple`
1696-
API.)
1697-
1698-
``NamedTuple`` subclasses can also have docstrings and methods::
1699-
1700-
class Employee(NamedTuple):
1701-
"""Represents an employee."""
1702-
name: str
1703-
id: int = 3
1704-
1705-
def __repr__(self) -> str:
1706-
return f'<Employee {self.name}, id={self.id}>'
1707-
1708-
``NamedTuple`` subclasses can be generic::
1709-
1710-
class Group(NamedTuple, Generic[T]):
1711-
key: T
1712-
group: list[T]
1713-
1714-
Backward-compatible usage::
1715-
1716-
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1717-
1718-
.. versionchanged:: 3.6
1719-
Added support for :pep:`526` variable annotation syntax.
1720-
1721-
.. versionchanged:: 3.6.1
1722-
Added support for default values, methods, and docstrings.
1723-
1724-
.. versionchanged:: 3.8
1725-
The ``_field_types`` and ``__annotations__`` attributes are
1726-
now regular dictionaries instead of instances of ``OrderedDict``.
1727-
1728-
.. versionchanged:: 3.9
1729-
Removed the ``_field_types`` attribute in favor of the more
1730-
standard ``__annotations__`` attribute which has the same information.
1731-
1732-
.. versionchanged:: 3.11
1733-
Added support for generic namedtuples.
1734-
1735-
.. class:: NewType(name, tp)
1736-
1737-
A helper class to indicate a distinct type to a typechecker,
1738-
see :ref:`distinct`. At runtime it returns an object that returns
1739-
its argument when called.
1740-
Usage::
1741-
1742-
UserId = NewType('UserId', int)
1743-
first_user = UserId(1)
1744-
1745-
.. versionadded:: 3.5.2
1746-
1747-
.. versionchanged:: 3.10
1748-
``NewType`` is now a class rather than a function.
1749-
17501750
.. class:: TypedDict(dict)
17511751

17521752
Special construct to add type hints to a dictionary.

0 commit comments

Comments
 (0)