Text of docs.python.org › uk › 3 › library › typing.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

typing — Support for type hints — Python 3.15.2 documentation

Навігація індекс модулі | наступний | попередній | Python » 3.15.2 documentation » The Python standard library » Засоби розробки » typing — Support for type hints | Theme | typing — Support for type hints ¶ Added in version 3.5. Вихідний код: Lib/typing.py Примітка The Python runtime does not enforce function and variable type annotations.

They can be used by third party tools such as type checkers , IDEs, linters, etc. This module provides runtime support for type hints. Consider the function below: def surface_area_of_cube ( edge_length : float ) -> str : return f "The surface area of the cube is { 6 * edge_length ** 2 } ." The function surface_area_of_cube takes an argument expected to be an instance of float , as indicated by the type hint edge_length: float .

The function is expected to return an instance of str , as indicated by the -> str hint. While type hints can be simple classes like float or str , they can also be more complex. The typing module provides a vocabulary of more advanced type hints. New features are frequently added to the typing module. The typing_extensions package provides backports of these new features to older versions of Python. Дивись також Typing cheat sheet A quick overview of type hints (hosted at the mypy docs) Type System Reference section of the mypy docs The Python typing system is standardised via PEPs, so this reference should broadly apply to most Python type checkers. (Some parts may still be specific to mypy.) Static Typing with Python Type-checker-agnostic documentation written by the community detailing type system features, useful typing related tools and typing best practices.

Specification for the Python Type System ¶ The canonical, up-to-date specification of the Python type system can be found at Specification for the Python type system . Псевдоніми типів ¶ A type alias is defined using the type statement, which creates an instance of TypeAliasType . In this example, Vector and list[float] will be treated equivalently by static type checkers: type Vector = list [ float ] def scale ( scalar : float , vector : Vector ) -> Vector : return [ scalar * num for num in vector ] # passes type checking; a list of floats qualifies as a Vector. new_vector = scale ( 2.0 , [ 1.0 , - 4.2 , 5.4 ]) Псевдоніми типів корисні для спрощення анотацій складних типів.

Наприклад: from collections.abc import Sequence type ConnectionOptions = dict [ str , str ] type Address = tuple [ str , int ] type Server = tuple [ Address , ConnectionOptions ] def broadcast_message ( message : str , servers : Sequence [ Server ]) -> None : ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message ( message : str , servers : Sequence [ tuple [ tuple [ str , int ], dict [ str , str ]]] ) -> None : ...

The type statement is new in Python 3.12. For backwards compatibility, type aliases can also be created through simple assignment: Vector = list [ float ] Or marked with TypeAlias to make it explicit that this is a type alias, not a normal variable assignment: from typing import TypeAlias Vector : TypeAlias = list [ float ] NewType ¶ Використовуйте помічник NewType для створення різних типів: from typing import NewType UserId = NewType ( 'UserId' , int ) some_id = UserId ( 524313 ) Аналізатор типів розглядатиме новий тип як підклас вихідного типу.

Це корисно для виявлення логічних помилок: def get_user_name ( user_id : UserId ) -> str : ... # passes type checking user_a = get_user_name ( UserId ( 42351 )) # fails type checking; an int is not a UserId user_b = get_user_name ( - 1 ) Ви все ще можете виконувати всі операції int зі змінною типу UserId , але результат завжди матиме тип int .

Це дозволяє передавати UserId усюди, де можна очікувати int , але запобігає випадковому створенню UserId недійсним способом: # 'output' is of type 'int', not 'UserId' output = UserId ( 23413 ) + UserId ( 54341 ) Зауважте, що ці перевірки виконуються лише засобом перевірки статичного типу.

Під час виконання оператор Derived = NewType('Derived', Base) зробить Derived викликом, який негайно повертає будь-який параметр, який ви йому передаєте. Це означає, що вираз Derived(some_value) не створює нового класу і не вносить багато додаткових витрат, крім звичайного виклику функції.

Точніше, вираз some_value is Derived(some_value) завжди вірний під час виконання. Неможливо створити підтип Derived : from typing import NewType UserId = NewType ( 'UserId' , int ) # Fails at runtime and does not pass type checking class AdminUserId ( UserId ): pass Однак можна створити NewType на основі «похідного» NewType : from typing import NewType UserId = NewType ( 'UserId' , int ) ProUserId = NewType ( 'ProUserId' , UserId ) і аналіз типів для ProUserId працюватиме належним чином.

Дивіться PEP 484 для більш детальної інформації. Примітка Recall that the use of a type alias declares two types to be equivalent to one another. Doing type Alias = Original will make the static type checker treat Alias as being exactly equivalent to Original in all cases. This is useful when you want to simplify complex type signatures. На відміну, NewType оголошує один тип як підтип іншого.

Якщо виконати Derived = NewType('Derived', Original) , аналізатор типів розглядатиме Derived як підклас Original , що означає значення типу Original не можна використовувати там, де очікується значення типу Derived . Це корисно, коли ви хочете запобігти логічним помилкам з мінімальними витратами на виконання.

Added in version 3.5.2. Змінено в версії 3.10: NewType is now a class rather than a function. As a result, there is some additional runtime cost when calling NewType over a regular function. Змінено в версії 3.11: The performance of calling NewType has been restored to its level in Python 3.9. Annotating callable objects ¶ Functions – or other callable objects – can be annotated using collections.abc.Callable or deprecated typing.Callable .

Callable[[int], str] signifies a function that takes a single parameter of type int and returns a str . Наприклад: from collections.abc import Callable , Awaitable def feeder ( get_next_item : Callable [[], str ]) -> None : ... # Body def async_query ( on_success : Callable [[ int ], None ], on_error : Callable [[ int , Exception ], None ]) -> None : ... # Body async def on_update ( value : str ) -> None : ... # Body callback : Callable [[ str ], Awaitable [ None ]] = on_update The subscription syntax must always be used with exactly two values: the argument list and the return type.

The argument list must be a list of types, a ParamSpec , Concatenate , or an ellipsis ( ... ). The return type must be a single type. If a literal ellipsis ... is given as the argument list, it indicates that a callable with any arbitrary parameter list woul

The rest of this page is on the live site.