tornado API Reference
Full documentation for tornado (Standard Library / Native)
tornado.importlib
Python Library Documentation: package importlib
NAME
importlib - A pure Python implementation of import.
MODULE REFERENCE
https://docs.python.org/3.12/library/importlib.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
PACKAGE CONTENTS
_abc
_bootstrap
_bootstrap_external
abc
machinery
metadata (package)
readers
resources (package)
simple
util
FUNCTIONS
__import__(name, globals=None, locals=None, fromlist=(), level=0)
Import a module.
The 'globals' argument is used to infer where the import is occurring from
to handle relative imports. The 'locals' argument is ignored. The
'fromlist' argument specifies what should exist as attributes on the module
being imported (e.g. ``from module import <fromlist>``). The 'level'
argument represents the package location to import from in a relative
import (e.g. ``from ..pkg import mod`` would have a 'level' of 2).
import_module(name, package=None)
Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
invalidate_caches()
Call the invalidate_caches() method on all meta path finders stored in
sys.meta_path (where implemented).
reload(module)
Reload the module and return it.
The module must have been successfully imported before.
DATA
__all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\importlib\__init__.py
tornado.typing
Python Library Documentation: module typing
NAME
typing - The typing module: Support for gradual typing as defined by PEP 484 and subsequent PEPs.
MODULE REFERENCE
https://docs.python.org/3.12/library/typing.html
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
Among other things, the module includes the following:
* Generic, Protocol, and internal machinery to support generic aliases.
All subscripted types like X[int], Union[int, str] are generic aliases.
* Various "special forms" that have unique meanings in type annotations:
NoReturn, Never, ClassVar, Self, Concatenate, Unpack, and others.
* Classes whose instances can be type arguments to generic classes and functions:
TypeVar, ParamSpec, TypeVarTuple.
* Public helper functions: get_type_hints, overload, cast, final, and others.
* Several protocols to support duck-typing:
SupportsFloat, SupportsIndex, SupportsAbs, and others.
* Special types: NewType, NamedTuple, TypedDict.
* Deprecated wrapper submodules for re and io related types.
* Deprecated aliases for builtin types and collections.abc ABCs.
Any name not present in __all__ is an implementation detail
that may be changed without notice. Use at your own risk!
CLASSES
builtins.object
builtins.str
Annotated
Any
Generic
IO
BinaryIO
TextIO
Protocol
SupportsAbs
SupportsBytes
SupportsComplex
SupportsFloat
SupportsIndex
SupportsInt
SupportsRound
NewType
ParamSpec
ParamSpecArgs
ParamSpecKwargs
TypeAliasType
TypeVar
TypeVarTuple
_Final(builtins.object)
ForwardRef
class Annotated(builtins.object)
| Annotated(*args, **kwargs)
|
| Add context-specific metadata to a type.
|
| Example: Annotated[int, runtime_check.Unsigned] indicates to the
| hypothetical runtime_check module that this type is an unsigned int.
| Every other consumer of this type can ignore this metadata and treat
| this type as int.
|
| The first argument to Annotated must be a valid type.
|
| Details:
|
| - It's an error to call `Annotated` with less than two arguments.
| - Access the metadata via the ``__metadata__`` attribute::
|
| assert Annotated[int, '$'].__metadata__ == ('$',)
|
| - Nested Annotated types are flattened::
|
| assert Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
|
| - Instantiating an annotated type is equivalent to instantiating the
| underlying type::
|
| assert Annotated[C, Ann1](5) == C(5)
|
| - Annotated can be used as a generic type alias::
|
| type Optimized[T] = Annotated[T, runtime.Optimize()]
| # type checker will treat Optimized[int]
| # as equivalent to Annotated[int, runtime.Optimize()]
|
| type OptimizedList[T] = Annotated[list[T], runtime.Optimize()]
| # type checker will treat OptimizedList[int]
| # as equivalent to Annotated[list[int], runtime.Optimize()]
|
| - Annotated cannot be used with an unpacked TypeVarTuple::
|
| type Variadic[*Ts] = Annotated[*Ts, Ann1] # NOT valid
|
| This would be equivalent to::
|
| Annotated[T1, T2, T3, ..., Ann1]
|
| where T1, T2 etc. are TypeVars, which would be invalid, because
| only one type should be passed to Annotated.
|
| Class methods defined here:
|
| __class_getitem__(params)
|
| __init_subclass__(*args, **kwargs)
| This method is called when a class is subclassed.
|
| The default implementation does nothing. It may be
| overridden to extend subclasses.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(cls, *args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
class Any(builtins.object)
| Any(*args, **kwargs)
|
| Special type indicating an unconstrained type.
|
| - Any is compatible with every type.
| - Any assumed to have all methods.
| - All values assumed to be instances of Any.
|
| Note that all the above statements are true from the point of view of
| static type checkers. At runtime, Any should not be used with instance
| checks.
|
| Static methods defined here:
|
| __new__(cls, *args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class BinaryIO(IO)
| Typed version of the return of open() in binary mode.
|
| Method resolution order:
| BinaryIO
| IO
| Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'BinaryIO'
|
| write(self, s: Union[bytes, bytearray]) -> int
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __orig_bases__ = (typing.IO[bytes],)
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from IO:
|
| __exit__(self, type, value, traceback) -> None
|
| close(self) -> None
|
| fileno(self) -> int
|
| flush(self) -> None
|
| isatty(self) -> bool
|
| read(self, n: int = -1) -> ~AnyStr
|
| readable(self) -> bool
|
| readline(self, limit: int = -1) -> ~AnyStr
|
| readlines(self, hint: int = -1) -> List[~AnyStr]
|
| seek(self, offset: int, whence: int = 0) -> int
|
| seekable(self) -> bool
|
| tell(self) -> int
|
| truncate(self, size: int = None) -> int
|
| writable(self) -> bool
|
| writelines(self, lines: List[~AnyStr]) -> None
|
| ----------------------------------------------------------------------
| Readonly properties inherited from IO:
|
| closed
|
| mode
|
| name
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class ForwardRef(_Final)
| ForwardRef(arg, is_argument=True, module=None, *, is_class=False)
|
| Internal wrapper to hold a forward reference.
|
| Method resolution order:
| ForwardRef
| _Final
| builtins.object
|
| Methods defined here:
|
| __eq__(self, other)
| Return self==value.
|
| __hash__(self)
| Return hash(self).
|
| __init__(self, arg, is_argument=True, module=None, *, is_class=False)
| Initialize self. See help(type(self)) for accurate signature.
|
| __or__(self, other)
| Return self|value.
|
| __repr__(self)
| Return repr(self).
|
| __ror__(self, other)
| Return value|self.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __forward_arg__
|
| __forward_code__
|
| __forward_evaluated__
|
| __forward_is_argument__
|
| __forward_is_class__
|
| __forward_module__
|
| __forward_value__
|
| ----------------------------------------------------------------------
| Class methods inherited from _Final:
|
| __init_subclass__(*args, **kwds)
| This method is called when a class is subclassed.
|
| The default implementation does nothing. It may be
| overridden to extend subclasses.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from _Final:
|
| __weakref__
| list of weak references to the object
class Generic(builtins.object)
| Abstract base class for generic types.
|
| On Python 3.12 and newer, generic classes implicitly inherit from
| Generic when they declare a parameter list after the class's name::
|
| class Mapping[KT, VT]:
| def __getitem__(self, key: KT) -> VT:
| ...
| # Etc.
|
| On older versions of Python, however, generic classes have to
| explicitly inherit from Generic.
|
| After a class has been declared to be generic, it can then be used as
| follows::
|
| def lookup_name[KT, VT](mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
| try:
| return mapping[key]
| except KeyError:
| return default
|
| Class methods defined here:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class IO(Generic)
| Generic base class for TextIO and BinaryIO.
|
| This is an abstract, generic version of the return of open().
|
| NOTE: This does not distinguish between the different possible
| classes (text vs. binary, read vs. write vs. read/write,
| append-only, unbuffered). The TextIO and BinaryIO subclasses
| below capture the distinctions between text vs. binary, which is
| pervasive in the interface; however we currently do not offer a
| way to track the other distinctions in the type system.
|
| Method resolution order:
| IO
| Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'IO[AnyStr]'
|
| __exit__(self, type, value, traceback) -> None
|
| close(self) -> None
|
| fileno(self) -> int
|
| flush(self) -> None
|
| isatty(self) -> bool
|
| read(self, n: int = -1) -> ~AnyStr
|
| readable(self) -> bool
|
| readline(self, limit: int = -1) -> ~AnyStr
|
| readlines(self, hint: int = -1) -> List[~AnyStr]
|
| seek(self, offset: int, whence: int = 0) -> int
|
| seekable(self) -> bool
|
| tell(self) -> int
|
| truncate(self, size: int = None) -> int
|
| writable(self) -> bool
|
| write(self, s: ~AnyStr) -> int
|
| writelines(self, lines: List[~AnyStr]) -> None
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| closed
|
| mode
|
| name
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __orig_bases__ = (typing.Generic[~AnyStr],)
|
| __parameters__ = (~AnyStr,)
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class NewType(builtins.object)
| NewType(name, tp)
|
| NewType creates simple unique types with almost zero runtime overhead.
|
| NewType(name, tp) is considered a subtype of tp
| by static type checkers. At runtime, NewType(name, tp) returns
| a dummy callable that simply returns its argument.
|
| Usage::
|
| UserId = NewType('UserId', int)
|
| def name_by_id(user_id: UserId) -> str:
| ...
|
| UserId('user') # Fails type check
|
| name_by_id(42) # Fails type check
| name_by_id(UserId(42)) # OK
|
| num = UserId(5) + 1 # type: int
|
| Methods defined here:
|
| __init__(self, name, tp)
| Initialize self. See help(type(self)) for accurate signature.
|
| __mro_entries__(self, bases)
|
| __or__(self, other)
| Return self|value.
|
| __reduce__(self)
| Helper for pickle.
|
| __repr__(self)
| Return repr(self).
|
| __ror__(self, other)
| Return value|self.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __call__ = _idfunc(x, /)
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
class ParamSpec(builtins.object)
| Parameter specification variable.
|
| The preferred way to construct a parameter specification is via the
| dedicated syntax for generic functions, classes, and type aliases,
| where the use of '**' creates a parameter specification::
|
| type IntFunc[**P] = Callable[P, int]
|
| For compatibility with Python 3.11 and earlier, ParamSpec objects
| can also be created as follows::
|
| P = ParamSpec('P')
|
| Parameter specification variables exist primarily for the benefit of
| static type checkers. They are used to forward the parameter types of
| one callable to another callable, a pattern commonly found in
| higher-order functions and decorators. They are only valid when used
| in ``Concatenate``, or as the first argument to ``Callable``, or as
| parameters for user-defined Generics. See class Generic for more
| information on generic types.
|
| An example for annotating a decorator::
|
| def add_logging[**P, T](f: Callable[P, T]) -> Callable[P, T]:
| '''A type-safe decorator to add logging to a function.'''
| def inner(*args: P.args, **kwargs: P.kwargs) -> T:
| logging.info(f'{f.__name__} was called')
| return f(*args, **kwargs)
| return inner
|
| @add_logging
| def add_two(x: float, y: float) -> float:
| '''Add two numbers together.'''
| return x + y
|
| Parameter specification variables can be introspected. e.g.::
|
| >>> P = ParamSpec("P")
| >>> P.__name__
| 'P'
|
| Note that only parameter specification variables defined in the global
| scope can be pickled.
|
| Methods defined here:
|
| __mro_entries__(...)
|
| __or__(self, value, /)
| Return self|value.
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __typing_prepare_subst__(self, /, alias, args)
|
| __typing_subst__(self, /, arg)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __bound__
|
| __contravariant__
|
| __covariant__
|
| __infer_variance__
|
| args
| Represents positional arguments.
|
| kwargs
| Represents keyword arguments.
class ParamSpecArgs(builtins.object)
| The args for a ParamSpec object.
|
| Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
|
| ParamSpecArgs objects have a reference back to their ParamSpec::
|
| >>> P = ParamSpec("P")
| >>> P.args.__origin__ is P
| True
|
| This type is meant for runtime introspection and has no special meaning
| to static type checkers.
|
| Methods defined here:
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mro_entries__(...)
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __origin__
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
class ParamSpecKwargs(builtins.object)
| The kwargs for a ParamSpec object.
|
| Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
|
| ParamSpecKwargs objects have a reference back to their ParamSpec::
|
| >>> P = ParamSpec("P")
| >>> P.kwargs.__origin__ is P
| True
|
| This type is meant for runtime introspection and has no special meaning
| to static type checkers.
|
| Methods defined here:
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __mro_entries__(...)
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __origin__
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
class Protocol(Generic)
| Base class for protocol classes.
|
| Protocol classes are defined as::
|
| class Proto(Protocol):
| def meth(self) -> int:
| ...
|
| Such classes are primarily used with static type checkers that recognize
| structural subtyping (static duck-typing).
|
| For example::
|
| class C:
| def meth(self) -> int:
| return 0
|
| def func(x: Proto) -> int:
| return x.meth()
|
| func(C()) # Passes static type check
|
| See PEP 544 for details. Protocol classes decorated with
| @typing.runtime_checkable act as simple-minded runtime protocols that check
| only the presence of given attributes, ignoring their type signatures.
| Protocol classes can be generic, they are defined as::
|
| class GenProto[T](Protocol):
| def meth(self) -> T:
| ...
|
| Method resolution order:
| Protocol
| Generic
| builtins.object
|
| Class methods defined here:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset()
|
| __parameters__ = ()
|
| __protocol_attrs__ = set()
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsAbs(Protocol)
| SupportsAbs(*args, **kwargs)
|
| An ABC with one abstract method __abs__ that is covariant in its return type.
|
| Method resolution order:
| SupportsAbs
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __abs__(self) -> T
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__abs__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __orig_bases__ = (<class 'typing.Protocol'>, typing.Generic[T])
|
| __parameters__ = (T,)
|
| __protocol_attrs__ = {'__abs__'}
|
| __type_params__ = (T,)
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsBytes(Protocol)
| SupportsBytes(*args, **kwargs)
|
| An ABC with one abstract method __bytes__.
|
| Method resolution order:
| SupportsBytes
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __bytes__(self) -> bytes
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__bytes__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__bytes__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsComplex(Protocol)
| SupportsComplex(*args, **kwargs)
|
| An ABC with one abstract method __complex__.
|
| Method resolution order:
| SupportsComplex
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __complex__(self) -> complex
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__complex__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__complex__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsFloat(Protocol)
| SupportsFloat(*args, **kwargs)
|
| An ABC with one abstract method __float__.
|
| Method resolution order:
| SupportsFloat
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __float__(self) -> float
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__float__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__float__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsIndex(Protocol)
| SupportsIndex(*args, **kwargs)
|
| An ABC with one abstract method __index__.
|
| Method resolution order:
| SupportsIndex
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __index__(self) -> int
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__index__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__index__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsInt(Protocol)
| SupportsInt(*args, **kwargs)
|
| An ABC with one abstract method __int__.
|
| Method resolution order:
| SupportsInt
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| __int__(self) -> int
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__int__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __parameters__ = ()
|
| __protocol_attrs__ = {'__int__'}
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
class SupportsRound(Protocol)
| SupportsRound(*args, **kwargs)
|
| An ABC with one abstract method __round__ that is covariant in its return type.
|
| Method resolution order:
| SupportsRound
| Protocol
| Generic
| builtins.object
|
| Methods defined here:
|
| __init__ = _no_init_or_replace_init(self, *args, **kwargs)
|
| __round__(self, ndigits: int = 0) -> T
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __subclasshook__ = _proto_hook(other)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __abstractmethods__ = frozenset({'__round__'})
|
| __annotations__ = {}
|
| __non_callable_proto_members__ = set()
|
| __orig_bases__ = (<class 'typing.Protocol'>, typing.Generic[T])
|
| __parameters__ = (T,)
|
| __protocol_attrs__ = {'__round__'}
|
| __type_params__ = (T,)
|
| ----------------------------------------------------------------------
| Class methods inherited from Protocol:
|
| __init_subclass__(*args, **kwargs)
| Function to initialize subclasses.
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
Text = class str(object)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return bool(key in self).
|
| __eq__(self, value, /)
| Return self==value.
|
| __format__(self, format_spec, /)
| Return a formatted version of the string as described by format_spec.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(...)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mod__(self, value, /)
| Return self%value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmod__(self, value, /)
| Return value%self.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __sizeof__(self, /)
| Return the size of the string in memory, in bytes.
|
| __str__(self, /)
| Return str(self).
|
| capitalize(self, /)
| Return a capitalized version of the string.
|
| More specifically, make the first character have upper case and the rest lower
| case.
|
| casefold(self, /)
| Return a version of the string suitable for caseless comparisons.
|
| center(self, width, fillchar=' ', /)
| Return a centered string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| count(...)
| S.count(sub[, start[, end]]) -> int
|
| Return the number of non-overlapping occurrences of substring sub in
| string S[start:end]. Optional arguments start and end are
| interpreted as in slice notation.
|
| encode(self, /, encoding='utf-8', errors='strict')
| Encode the string using the codec registered for encoding.
|
| encoding
| The encoding in which to encode the string.
| errors
| The error handling scheme to use for encoding errors.
| The default is 'strict' meaning that encoding errors raise a
| UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
| 'xmlcharrefreplace' as well as any other name registered with
| codecs.register_error that can handle UnicodeEncodeErrors.
|
| endswith(...)
| S.endswith(suffix[, start[, end]]) -> bool
|
| Return True if S ends with the specified suffix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| suffix can also be a tuple of strings to try.
|
| expandtabs(self, /, tabsize=8)
| Return a copy where all tab characters are expanded using spaces.
|
| If tabsize is not given, a tab size of 8 characters is assumed.
|
| find(...)
| S.find(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
|
| format_map(...)
| S.format_map(mapping) -> str
|
| Return a formatted version of S, using substitutions from mapping.
| The substitutions are identified by braces ('{' and '}').
|
| index(...)
| S.index(sub[, start[, end]]) -> int
|
| Return the lowest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| isalnum(self, /)
| Return True if the string is an alpha-numeric string, False otherwise.
|
| A string is alpha-numeric if all characters in the string are alpha-numeric and
| there is at least one character in the string.
|
| isalpha(self, /)
| Return True if the string is an alphabetic string, False otherwise.
|
| A string is alphabetic if all characters in the string are alphabetic and there
| is at least one character in the string.
|
| isascii(self, /)
| Return True if all characters in the string are ASCII, False otherwise.
|
| ASCII characters have code points in the range U+0000-U+007F.
| Empty string is ASCII too.
|
| isdecimal(self, /)
| Return True if the string is a decimal string, False otherwise.
|
| A string is a decimal string if all characters in the string are decimal and
| there is at least one character in the string.
|
| isdigit(self, /)
| Return True if the string is a digit string, False otherwise.
|
| A string is a digit string if all characters in the string are digits and there
| is at least one character in the string.
|
| isidentifier(self, /)
| Return True if the string is a valid Python identifier, False otherwise.
|
| Call keyword.iskeyword(s) to test whether string s is a reserved identifier,
| such as "def" or "class".
|
| islower(self, /)
| Return True if the string is a lowercase string, False otherwise.
|
| A string is lowercase if all cased characters in the string are lowercase and
| there is at least one cased character in the string.
|
| isnumeric(self, /)
| Return True if the string is a numeric string, False otherwise.
|
| A string is numeric if all characters in the string are numeric and there is at
| least one character in the string.
|
| isprintable(self, /)
| Return True if the string is printable, False otherwise.
|
| A string is printable if all of its characters are considered printable in
| repr() or if it is empty.
|
| isspace(self, /)
| Return True if the string is a whitespace string, False otherwise.
|
| A string is whitespace if all characters in the string are whitespace and there
| is at least one character in the string.
|
| istitle(self, /)
| Return True if the string is a title-cased string, False otherwise.
|
| In a title-cased string, upper- and title-case characters may only
| follow uncased characters and lowercase characters only cased ones.
|
| isupper(self, /)
| Return True if the string is an uppercase string, False otherwise.
|
| A string is uppercase if all cased characters in the string are uppercase and
| there is at least one cased character in the string.
|
| join(self, iterable, /)
| Concatenate any number of strings.
|
| The string whose method is called is inserted in between each given string.
| The result is returned as a new string.
|
| Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
|
| ljust(self, width, fillchar=' ', /)
| Return a left-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| lower(self, /)
| Return a copy of the string converted to lowercase.
|
| lstrip(self, chars=None, /)
| Return a copy of the string with leading whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| partition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string. If the separator is found,
| returns a 3-tuple containing the part before the separator, the separator
| itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing the original string
| and two empty strings.
|
| removeprefix(self, prefix, /)
| Return a str with the given prefix string removed if present.
|
| If the string starts with the prefix string, return string[len(prefix):].
| Otherwise, return a copy of the original string.
|
| removesuffix(self, suffix, /)
| Return a str with the given suffix string removed if present.
|
| If the string ends with the suffix string and that suffix is not empty,
| return string[:-len(suffix)]. Otherwise, return a copy of the original
| string.
|
| replace(self, old, new, count=-1, /)
| Return a copy with all occurrences of substring old replaced by new.
|
| count
| Maximum number of occurrences to replace.
| -1 (the default value) means replace all occurrences.
|
| If the optional argument count is given, only the first count occurrences are
| replaced.
|
| rfind(...)
| S.rfind(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Return -1 on failure.
|
| rindex(...)
| S.rindex(sub[, start[, end]]) -> int
|
| Return the highest index in S where substring sub is found,
| such that sub is contained within S[start:end]. Optional
| arguments start and end are interpreted as in slice notation.
|
| Raises ValueError when the substring is not found.
|
| rjust(self, width, fillchar=' ', /)
| Return a right-justified string of length width.
|
| Padding is done using the specified fill character (default is a space).
|
| rpartition(self, sep, /)
| Partition the string into three parts using the given separator.
|
| This will search for the separator in the string, starting at the end. If
| the separator is found, returns a 3-tuple containing the part before the
| separator, the separator itself, and the part after it.
|
| If the separator is not found, returns a 3-tuple containing two empty strings
| and the original string.
|
| rsplit(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the end of the string and works to the front.
|
| rstrip(self, chars=None, /)
| Return a copy of the string with trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| split(self, /, sep=None, maxsplit=-1)
| Return a list of the substrings in the string, using sep as the separator string.
|
| sep
| The separator used to split the string.
|
| When set to None (the default value), will split on any whitespace
| character (including \n \r \t \f and spaces) and will discard
| empty strings from the result.
| maxsplit
| Maximum number of splits.
| -1 (the default value) means no limit.
|
| Splitting starts at the front of the string and works to the end.
|
| Note, str.split() is mainly useful for data that has been intentionally
| delimited. With natural text that includes punctuation, consider using
| the regular expression module.
|
| splitlines(self, /, keepends=False)
| Return a list of the lines in the string, breaking at line boundaries.
|
| Line breaks are not included in the resulting list unless keepends is given and
| true.
|
| startswith(...)
| S.startswith(prefix[, start[, end]]) -> bool
|
| Return True if S starts with the specified prefix, False otherwise.
| With optional start, test S beginning at that position.
| With optional end, stop comparing S at that position.
| prefix can also be a tuple of strings to try.
|
| strip(self, chars=None, /)
| Return a copy of the string with leading and trailing whitespace removed.
|
| If chars is given and not None, remove characters in chars instead.
|
| swapcase(self, /)
| Convert uppercase characters to lowercase and lowercase characters to uppercase.
|
| title(self, /)
| Return a version of the string where each word is titlecased.
|
| More specifically, words start with uppercased characters and all remaining
| cased characters have lower case.
|
| translate(self, table, /)
| Replace each character in the string using the given translation table.
|
| table
| Translation table, which must be a mapping of Unicode ordinals to
| Unicode ordinals, strings, or None.
|
| The table must implement lookup/indexing via __getitem__, for instance a
| dictionary or list. If this operation raises LookupError, the character is
| left untouched. Characters mapped to None are deleted.
|
| upper(self, /)
| Return a copy of the string converted to uppercase.
|
| zfill(self, width, /)
| Pad a numeric string with zeros on the left, to fill a field of the given width.
|
| The string is never truncated.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| maketrans(...)
| Return a translation table usable for str.translate().
|
| If there is only one argument, it must be a dictionary mapping Unicode
| ordinals (integers) or characters to Unicode ordinals, strings or None.
| Character keys will be then converted to ordinals.
| If there are two arguments, they must be strings of equal length, and
| in the resulting dictionary, each character in x will be mapped to the
| character at the same position in y. If there is a third argument, it
| must be a string, whose characters will be mapped to None in the result.
class TextIO(IO)
| Typed version of the return of open() in text mode.
|
| Method resolution order:
| TextIO
| IO
| Generic
| builtins.object
|
| Methods defined here:
|
| __enter__(self) -> 'TextIO'
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| buffer
|
| encoding
|
| errors
|
| line_buffering
|
| newlines
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __annotations__ = {}
|
| __orig_bases__ = (typing.IO[str],)
|
| __parameters__ = ()
|
| ----------------------------------------------------------------------
| Methods inherited from IO:
|
| __exit__(self, type, value, traceback) -> None
|
| close(self) -> None
|
| fileno(self) -> int
|
| flush(self) -> None
|
| isatty(self) -> bool
|
| read(self, n: int = -1) -> ~AnyStr
|
| readable(self) -> bool
|
| readline(self, limit: int = -1) -> ~AnyStr
|
| readlines(self, hint: int = -1) -> List[~AnyStr]
|
| seek(self, offset: int, whence: int = 0) -> int
|
| seekable(self) -> bool
|
| tell(self) -> int
|
| truncate(self, size: int = None) -> int
|
| writable(self) -> bool
|
| write(self, s: ~AnyStr) -> int
|
| writelines(self, lines: List[~AnyStr]) -> None
|
| ----------------------------------------------------------------------
| Readonly properties inherited from IO:
|
| closed
|
| mode
|
| name
|
| ----------------------------------------------------------------------
| Class methods inherited from Generic:
|
| __class_getitem__(...)
| Parameterizes a generic class.
|
| At least, parameterizing a generic class is the *main* thing this
| method does. For example, for some generic class `Foo`, this is called
| when we do `Foo[int]` - there, with `cls=Foo` and `params=int`.
|
| However, note that this method is also called when defining generic
| classes in the first place with `class Foo[T]: ...`.
|
| __init_subclass__(...)
| Function to initialize subclasses.
class TypeAliasType(builtins.object)
| Type alias.
|
| Type aliases are created through the type statement::
|
| type Alias = int
|
| In this example, Alias and int will be treated equivalently by static
| type checkers.
|
| At runtime, Alias is an instance of TypeAliasType. The __name__
| attribute holds the name of the type alias. The value of the type alias
| is stored in the __value__ attribute. It is evaluated lazily, so the
| value is computed only if the attribute is accessed.
|
| Type aliases can also be generic::
|
| type ListOrSet[T] = list[T] | set[T]
|
| In this case, the type parameters of the alias are stored in the
| __type_params__ attribute.
|
| See PEP 695 for more information.
|
| Methods defined here:
|
| __getitem__(self, key, /)
| Return self[key].
|
| __or__(self, value, /)
| Return self|value.
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __parameters__
|
| __type_params__
|
| __value__
class TypeVar(builtins.object)
| Type variable.
|
| The preferred way to construct a type variable is via the dedicated
| syntax for generic functions, classes, and type aliases::
|
| class Sequence[T]: # T is a TypeVar
| ...
|
| This syntax can also be used to create bound and constrained type
| variables::
|
| # S is a TypeVar bound to str
| class StrSequence[S: str]:
| ...
|
| # A is a TypeVar constrained to str or bytes
| class StrOrBytesSequence[A: (str, bytes)]:
| ...
|
| However, if desired, reusable type variables can also be constructed
| manually, like so::
|
| T = TypeVar('T') # Can be anything
| S = TypeVar('S', bound=str) # Can be any subtype of str
| A = TypeVar('A', str, bytes) # Must be exactly str or bytes
|
| Type variables exist primarily for the benefit of static type
| checkers. They serve as the parameters for generic types as well
| as for generic function and type alias definitions.
|
| The variance of type variables is inferred by type checkers when they
| are created through the type parameter syntax and when
| ``infer_variance=True`` is passed. Manually created type variables may
| be explicitly marked covariant or contravariant by passing
| ``covariant=True`` or ``contravariant=True``. By default, manually
| created type variables are invariant. See PEP 484 and PEP 695 for more
| details.
|
| Methods defined here:
|
| __mro_entries__(...)
|
| __or__(self, value, /)
| Return self|value.
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __ror__(self, value, /)
| Return value|self.
|
| __typing_subst__(self, /, arg)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __bound__
|
| __constraints__
|
| __contravariant__
|
| __covariant__
|
| __infer_variance__
class TypeVarTuple(builtins.object)
| Type variable tuple. A specialized form of type variable that enables
| variadic generics.
|
| The preferred way to construct a type variable tuple is via the
| dedicated syntax for generic functions, classes, and type aliases,
| where a single '*' indicates a type variable tuple::
|
| def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
| return (*tup[1:], tup[0])
|
| For compatibility with Python 3.11 and earlier, TypeVarTuple objects
| can also be created as follows::
|
| Ts = TypeVarTuple('Ts') # Can be given any name
|
| Just as a TypeVar (type variable) is a placeholder for a single type,
| a TypeVarTuple is a placeholder for an *arbitrary* number of types. For
| example, if we define a generic class using a TypeVarTuple::
|
| class C[*Ts]: ...
|
| Then we can parameterize that class with an arbitrary number of type
| arguments::
|
| C[int] # Fine
| C[int, str] # Also fine
| C[()] # Even this is fine
|
| For more details, see PEP 646.
|
| Note that only TypeVarTuples defined in the global scope can be
| pickled.
|
| Methods defined here:
|
| __iter__(self, /)
| Implement iter(self).
|
| __mro_entries__(...)
|
| __reduce__(self, /)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| __typing_prepare_subst__(self, /, alias, args)
|
| __typing_subst__(self, /, arg)
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
FUNCTIONS
NamedTuple(typename, fields=None, /, **kwargs)
Typed version of namedtuple.
Usage::
class Employee(NamedTuple):
name: str
id: int
This is equivalent to::
Employee = collections.namedtuple('Employee', ['name', 'id'])
The resulting class has an extra __annotations__ attribute, giving a
dict that maps field names to types. (The field names are also in
the _fields attribute, which is part of the namedtuple API.)
An alternative equivalent functional syntax is also accepted::
Employee = NamedTuple('Employee', [('name', str), ('id', int)])
TypedDict(typename, fields=None, /, *, total=True, **kwargs)
A simple typed namespace. At runtime it is equivalent to a plain dict.
TypedDict creates a dictionary type such that a type checker will expect all
instances to have a certain set of keys, where each key is
associated with a value of a consistent type. This expectation
is not checked at runtime.
Usage::
>>> class Point2D(TypedDict):
... x: int
... y: int
... label: str
...
>>> a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
>>> b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
>>> Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
True
The type info can be accessed via the Point2D.__annotations__ dict, and
the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
TypedDict supports an additional equivalent form::
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
By default, all keys must be present in a TypedDict. It is possible
to override this by specifying totality::
class Point2D(TypedDict, total=False):
x: int
y: int
This means that a Point2D TypedDict can have any of the keys omitted. A type
checker is only expected to support a literal False or True as the value of
the total argument. True is the default, and makes all items defined in the
class body be required.
The Required and NotRequired special forms can also be used to mark
individual keys as being required or not required::
class Point2D(TypedDict):
x: int # the "x" key must always be present (Required is the default)
y: NotRequired[int] # the "y" key can be omitted
See PEP 655 for more details on Required and NotRequired.
assert_never(arg: Never, /) -> Never
Statically assert that a line of code is unreachable.
Example::
def int_or_str(arg: int | str) -> None:
match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _:
assert_never(arg)
If a type checker finds that a call to assert_never() is
reachable, it will emit an error.
At runtime, this throws an exception when called.
assert_type(val, typ, /)
Ask a static type checker to confirm that the value is of the given type.
At runtime this does nothing: it returns the first argument unchanged with no
checks or side effects, no matter the actual type of the argument.
When a static type checker encounters a call to assert_type(), it
emits an error if the value is not of the specified type::
def greet(name: str) -> None:
assert_type(name, str) # OK
assert_type(name, int) # type checker error
cast(typ, val)
Cast a value to a type.
This returns the value unchanged. To the type checker this
signals that the return value has the designated type, but at
runtime we intentionally don't check anything (we want this
to be as fast as possible).
clear_overloads()
Clear all overloads in the registry.
dataclass_transform(*, eq_default: bool = True, order_default: bool = False, kw_only_default: bool = False, frozen_default: bool = False, field_specifiers: tuple[typing.Union[type[typing.Any], typing.Callable[..., typing.Any]], ...] = (), **kwargs: Any) -> <class '_IdentityCallable'>
Decorator to mark an object as providing dataclass-like behaviour.
The decorator can be applied to a function, class, or metaclass.
Example usage with a decorator function::
@dataclass_transform()
def create_model[T](cls: type[T]) -> type[T]:
...
return cls
@create_model
class CustomerModel:
id: int
name: str
On a base class::
@dataclass_transform()
class ModelBase: ...
class CustomerModel(ModelBase):
id: int
name: str
On a metaclass::
@dataclass_transform()
class ModelMeta(type): ...
class ModelBase(metaclass=ModelMeta): ...
class CustomerModel(ModelBase):
id: int
name: str
The ``CustomerModel`` classes defined above will
be treated by type checkers similarly to classes created with
``@dataclasses.dataclass``.
For example, type checkers will assume these classes have
``__init__`` methods that accept ``id`` and ``name``.
The arguments to this decorator can be used to customize this behavior:
- ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
``True`` or ``False`` if it is omitted by the caller.
- ``order_default`` indicates whether the ``order`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``kw_only_default`` indicates whether the ``kw_only`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``frozen_default`` indicates whether the ``frozen`` parameter is
assumed to be True or False if it is omitted by the caller.
- ``field_specifiers`` specifies a static list of supported classes
or functions that describe fields, similar to ``dataclasses.field()``.
- Arbitrary other keyword arguments are accepted in order to allow for
possible future extensions.
At runtime, this decorator records its arguments in the
``__dataclass_transform__`` attribute on the decorated object.
It has no other runtime effect.
See PEP 681 for more details.
final(f)
Decorator to indicate final methods and final classes.
Use this decorator to indicate to type checkers that the decorated
method cannot be overridden, and decorated class cannot be subclassed.
For example::
class Base:
@final
def done(self) -> None:
...
class Sub(Base):
def done(self) -> None: # Error reported by type checker
...
@final
class Leaf:
...
class Other(Leaf): # Error reported by type checker
...
There is no runtime checking of these properties. The decorator
attempts to set the ``__final__`` attribute to ``True`` on the decorated
object to allow runtime introspection.
get_args(tp)
Get type arguments with all substitutions performed.
For unions, basic simplifications used by Union constructor are performed.
Examples::
>>> T = TypeVar('T')
>>> assert get_args(Dict[str, int]) == (str, int)
>>> assert get_args(int) == ()
>>> assert get_args(Union[int, Union[T, int], str][int]) == (int, str)
>>> assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
>>> assert get_args(Callable[[], T][int]) == ([], int)
get_origin(tp)
Get the unsubscripted version of a type.
This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar,
Annotated, and others. Return None for unsupported types.
Examples::
>>> P = ParamSpec('P')
>>> assert get_origin(Literal[42]) is Literal
>>> assert get_origin(int) is None
>>> assert get_origin(ClassVar[int]) is ClassVar
>>> assert get_origin(Generic) is Generic
>>> assert get_origin(Generic[T]) is Generic
>>> assert get_origin(Union[T, int]) is Union
>>> assert get_origin(List[Tuple[T, T]][int]) is list
>>> assert get_origin(P.args) is P
get_overloads(func)
Return all defined overloads for *func* as a sequence.
get_type_hints(obj, globalns=None, localns=None, include_extras=False)
Return type hints for an object.
This is often the same as obj.__annotations__, but it handles
forward references encoded as string literals and recursively replaces all
'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
The argument may be a module, class, method, or function. The annotations
are returned as a dictionary. For classes, annotations include also
inherited members.
TypeError is raised if the argument is not of a type that can contain
annotations, and an empty dictionary is returned if no annotations are
present.
BEWARE -- the behavior of globalns and localns is counterintuitive
(unless you are familiar with how eval() and exec() work). The
search order is locals first, then globals.
- If no dict arguments are passed, an attempt is made to use the
globals from obj (or the respective module's globals for classes),
and these are also used as the locals. If the object does not appear
to have globals, an empty dictionary is used. For classes, the search
order is globals first then locals.
- If one dict argument is passed, it is used for both globals and
locals.
- If two dict arguments are passed, they specify globals and
locals, respectively.
is_typeddict(tp)
Check if an annotation is a TypedDict class.
For example::
>>> from typing import TypedDict
>>> class Film(TypedDict):
... title: str
... year: int
...
>>> is_typeddict(Film)
True
>>> is_typeddict(dict)
False
no_type_check(arg)
Decorator to indicate that annotations are not type hints.
The argument must be a class or function; if it is a class, it
applies recursively to all methods and classes defined in that class
(but not to methods defined in its superclasses or subclasses).
This mutates the function(s) or class(es) in place.
no_type_check_decorator(decorator)
Decorator to give another decorator the @no_type_check effect.
This wraps the decorator with something that wraps the decorated
function in @no_type_check.
overload(func)
Decorator for overloaded functions/methods.
In a stub file, place two or more stub definitions for the same
function in a row, each decorated with @overload.
For example::
@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...
In a non-stub file (i.e. a regular .py file), do the same but
follow it with an implementation. The implementation should *not*
be decorated with @overload::
@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...
def utf8(value):
... # implementation goes here
The overloads for a function can be retrieved at runtime using the
get_overloads() function.
override(method: F, /) -> F
Indicate that a method is intended to override a method in a base class.
Usage::
class Base:
def method(self) -> None:
pass
class Child(Base):
@override
def method(self) -> None:
super().method()
When this decorator is applied to a method, the type checker will
validate that it overrides a method or attribute with the same name on a
base class. This helps prevent bugs that may occur when a base class is
changed without an equivalent change to a child class.
There is no runtime checking of this property. The decorator attempts to
set the ``__override__`` attribute to ``True`` on the decorated object to
allow runtime introspection.
See PEP 698 for details.
reveal_type(obj: T, /) -> T
Ask a static type checker to reveal the inferred type of an expression.
When a static type checker encounters a call to ``reveal_type()``,
it will emit the inferred type of the argument::
x: int = 1
reveal_type(x)
Running a static type checker (e.g., mypy) on this example
will produce output similar to 'Revealed type is "builtins.int"'.
At runtime, the function prints the runtime type of the
argument and returns the argument unchanged.
runtime_checkable(cls)
Mark a protocol class as a runtime protocol.
Such protocol can be used with isinstance() and issubclass().
Raise TypeError if applied to a non-protocol class.
This allows a simple-minded structural check very similar to
one trick ponies in collections.abc such as Iterable.
For example::
@runtime_checkable
class Closable(Protocol):
def close(self): ...
assert isinstance(open('/some/file'), Closable)
Warning: this will check only the presence of the required methods,
not their type signatures!
DATA
AbstractSet = typing.AbstractSet
A generic version of collections.abc.Set.
AnyStr = ~AnyStr
AsyncContextManager = typing.AsyncContextManager
A generic version of contextlib.AbstractAsyncContextManager.
AsyncGenerator = typing.AsyncGenerator
A generic version of collections.abc.AsyncGenerator.
AsyncIterable = typing.AsyncIterable
A generic version of collections.abc.AsyncIterable.
AsyncIterator = typing.AsyncIterator
A generic version of collections.abc.AsyncIterator.
Awaitable = typing.Awaitable
A generic version of collections.abc.Awaitable.
ByteString = typing.ByteString
A generic version of collections.abc.ByteString.
Callable = typing.Callable
Deprecated alias to collections.abc.Callable.
Callable[[int], str] signifies a function that takes a single
parameter of type int and returns a str.
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 ellipsis. The return type must be a single type.
There is no syntax to indicate optional or keyword arguments;
such function types are rarely used as callback types.
ChainMap = typing.ChainMap
A generic version of collections.ChainMap.
ClassVar = typing.ClassVar
Special type construct to mark class variables.
An annotation wrapped in ClassVar indicates that a given
attribute is intended to be used as a class variable and
should not be set on instances of that class.
Usage::
class Starship:
stats: ClassVar[dict[str, int]] = {} # class variable
damage: int = 10 # instance variable
ClassVar accepts only types and cannot be further subscribed.
Note that ClassVar is not a class itself, and should not
be used with isinstance() or issubclass().
Collection = typing.Collection
A generic version of collections.abc.Collection.
Concatenate = typing.Concatenate
Special form for annotating higher-order functions.
``Concatenate`` can be used in conjunction with ``ParamSpec`` and
``Callable`` to represent a higher-order function which adds, removes or
transforms the parameters of a callable.
For example::
Callable[Concatenate[int, P], int]
See PEP 612 for detailed information.
Container = typing.Container
A generic version of collections.abc.Container.
ContextManager = typing.ContextManager
A generic version of contextlib.AbstractContextManager.
Coroutine = typing.Coroutine
A generic version of collections.abc.Coroutine.
Counter = typing.Counter
A generic version of collections.Counter.
DefaultDict = typing.DefaultDict
A generic version of collections.defaultdict.
Deque = typing.Deque
A generic version of collections.deque.
Dict = typing.Dict
A generic version of dict.
Final = typing.Final
Special typing construct to indicate final names to type checkers.
A final name cannot be re-assigned or overridden in a subclass.
For example::
MAX_SIZE: Final = 9000
MAX_SIZE += 1 # Error reported by type checker
class Connection:
TIMEOUT: Final[int] = 10
class FastConnector(Connection):
TIMEOUT = 1 # Error reported by type checker
There is no runtime checking of these properties.
FrozenSet = typing.FrozenSet
A generic version of frozenset.
Generator = typing.Generator
A generic version of collections.abc.Generator.
Hashable = typing.Hashable
A generic version of collections.abc.Hashable.
ItemsView = typing.ItemsView
A generic version of collections.abc.ItemsView.
Iterable = typing.Iterable
A generic version of collections.abc.Iterable.
Iterator = typing.Iterator
A generic version of collections.abc.Iterator.
KeysView = typing.KeysView
A generic version of collections.abc.KeysView.
List = typing.List
A generic version of list.
Literal = typing.Literal
Special typing form to define literal types (a.k.a. value types).
This form can be used to indicate to type checkers that the corresponding
variable or function parameter has a value equivalent to the provided
literal (or one of several literals)::
def validate_simple(data: Any) -> Literal[True]: # always returns True
...
MODE = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: MODE) -> str:
...
open_helper('/some/path', 'r') # Passes type check
open_helper('/other/path', 'typo') # Error in type checker
Literal[...] cannot be subclassed. At runtime, an arbitrary value
is allowed as type argument to Literal[...], but type checkers may
impose restrictions.
LiteralString = typing.LiteralString
Represents an arbitrary literal string.
Example::
from typing import LiteralString
def run_query(sql: LiteralString) -> None:
...
def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
run_query("SELECT * FROM students") # OK
run_query(literal_string) # OK
run_query("SELECT * FROM " + literal_string) # OK
run_query(arbitrary_string) # type checker error
run_query( # type checker error
f"SELECT * FROM students WHERE name = {arbitrary_string}"
)
Only string literals and other LiteralStrings are compatible
with LiteralString. This provides a tool to help prevent
security issues such as SQL injection.
Mapping = typing.Mapping
A generic version of collections.abc.Mapping.
MappingView = typing.MappingView
A generic version of collections.abc.MappingView.
Match = typing.Match
A generic version of re.Match.
MutableMapping = typing.MutableMapping
A generic version of collections.abc.MutableMapping.
MutableSequence = typing.MutableSequence
A generic version of collections.abc.MutableSequence.
MutableSet = typing.MutableSet
A generic version of collections.abc.MutableSet.
Never = typing.Never
The bottom type, a type that has no members.
This can be used to define a function that should never be
called, or a function that never returns::
from typing import Never
def never_call_me(arg: Never) -> None:
pass
def int_or_str(arg: int | str) -> None:
never_call_me(arg) # type checker error
match arg:
case int():
print("It's an int")
case str():
print("It's a str")
case _:
never_call_me(arg) # OK, arg is of type Never
NoReturn = typing.NoReturn
Special type indicating functions that never return.
Example::
from typing import NoReturn
def stop() -> NoReturn:
raise Exception('no way')
NoReturn can also be used as a bottom type, a type that
has no values. Starting in Python 3.11, the Never type should
be used for this concept instead. Type checkers should treat the two
equivalently.
NotRequired = typing.NotRequired
Special typing construct to mark a TypedDict key as potentially missing.
For example::
class Movie(TypedDict):
title: str
year: NotRequired[int]
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
Optional = typing.Optional
Optional[X] is equivalent to Union[X, None].
OrderedDict = typing.OrderedDict
A generic version of collections.OrderedDict.
Pattern = typing.Pattern
A generic version of re.Pattern.
Required = typing.Required
Special typing construct to mark a TypedDict key as required.
This is mainly useful for total=False TypedDicts.
For example::
class Movie(TypedDict, total=False):
title: Required[str]
year: int
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
There is no runtime checking that a required key is actually provided
when instantiating a related TypedDict.
Reversible = typing.Reversible
A generic version of collections.abc.Reversible.
Self = typing.Self
Used to spell the type of "self" in classes.
Example::
from typing import Self
class Foo:
def return_self(self) -> Self:
...
return self
This is especially useful for:
- classmethods that are used as alternative constructors
- annotating an `__enter__` method which returns self
Sequence = typing.Sequence
A generic version of collections.abc.Sequence.
Set = typing.Set
A generic version of set.
Sized = typing.Sized
A generic version of collections.abc.Sized.
TYPE_CHECKING = False
Tuple = typing.Tuple
Deprecated alias to builtins.tuple.
Tuple[X, Y] is the cross-product type of X and Y.
Example: Tuple[T1, T2] is a tuple of two elements corresponding
to type variables T1 and T2. Tuple[int, float, str] is a tuple
of an int, a float and a string.
To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
Type = typing.Type
Deprecated alias to builtins.type.
builtins.type or typing.Type can be used to annotate class objects.
For example, suppose we have the following classes::
class User: ... # Abstract base for User classes
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...
And a function that takes a class argument that's a subclass of
User and returns an instance of the corresponding class::
def new_user[U](user_class: Type[U]) -> U:
user = user_class()
# (Here we could write the user object to a database)
return user
joe = new_user(BasicUser)
At this point the type checker knows that joe has type BasicUser.
TypeAlias = typing.TypeAlias
Special form for marking type aliases.
Use TypeAlias to indicate that an assignment should
be recognized as a proper type alias definition by type
checkers.
For example::
Predicate: TypeAlias = Callable[..., bool]
It's invalid when used anywhere except as in the example above.
TypeGuard = typing.TypeGuard
Special typing construct for marking user-defined type guard functions.
``TypeGuard`` can be used to annotate the return type of a user-defined
type guard function. ``TypeGuard`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean.
``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
type checkers to determine a more precise type of an expression within a
program's code flow. Usually type narrowing is done by analyzing
conditional code flow and applying the narrowing to a block of code. The
conditional expression here is sometimes referred to as a "type guard".
Sometimes it would be convenient to use a user-defined boolean function
as a type guard. Such a function should use ``TypeGuard[...]`` as its
return type to alert static type checkers to this intention.
Using ``-> TypeGuard`` tells the static type checker that for a given
function:
1. The return value is a boolean.
2. If the return value is ``True``, the type of its argument
is the type inside ``TypeGuard``.
For example::
def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
'''Determines whether all objects in the list are strings'''
return all(isinstance(x, str) for x in val)
def func1(val: list[object]):
if is_str_list(val):
# Type of ``val`` is narrowed to ``list[str]``.
print(" ".join(val))
else:
# Type of ``val`` remains as ``list[object]``.
print("Not a list of strings!")
Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
form of ``TypeA`` (it can even be a wider form) and this may lead to
type-unsafe results. 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. The responsibility of
writing type-safe type guards is left to the user.
``TypeGuard`` also works with type variables. For more information, see
PEP 647 (User-Defined Type Guards).
Union = typing.Union
Union type; Union[X, Y] means either X or Y.
On Python 3.10 and higher, the | operator
can also be used to denote unions;
X | Y means the same thing to the type checker as Union[X, Y].
To define a union, use e.g. Union[int, str]. Details:
- The arguments must be types and there must be at least one.
- None as an argument is a special case and is replaced by
type(None).
- Unions of unions are flattened, e.g.::
assert Union[Union[int, str], float] == Union[int, str, float]
- Unions of a single argument vanish, e.g.::
assert Union[int] == int # The constructor actually returns int
- Redundant arguments are skipped, e.g.::
assert Union[int, str, int] == Union[int, str]
- When comparing unions, the argument order is ignored, e.g.::
assert Union[int, str] == Union[str, int]
- You cannot subclass or instantiate a union.
- You can use Optional[X] as a shorthand for Union[X, None].
Unpack = typing.Unpack
Type unpack operator.
The type unpack operator takes the child types from some container type,
such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'.
For example::
# For some generic class `Foo`:
Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
Ts = TypeVarTuple('Ts')
# Specifies that `Bar` is generic in an arbitrary number of types.
# (Think of `Ts` as a tuple of an arbitrary number of individual
# `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
# `Generic[]`.)
class Bar(Generic[Unpack[Ts]]): ...
Bar[int] # Valid
Bar[int, str] # Also valid
From Python 3.11, this can also be done using the `*` operator::
Foo[*tuple[int, str]]
class Bar(Generic[*Ts]): ...
And from Python 3.12, it can be done using built-in syntax for generics::
Foo[*tuple[int, str]]
class Bar[*Ts]: ...
The operator can also be used along with a `TypedDict` to annotate
`**kwargs` in a function signature::
class Movie(TypedDict):
name: str
year: int
# This function expects two keyword arguments - *name* of type `str` and
# *year* of type `int`.
def foo(**kwargs: Unpack[Movie]): ...
Note that there is only some runtime checking of this operator. Not
everything the runtime allows may be accepted by static type checkers.
For more information, see PEPs 646 and 692.
ValuesView = typing.ValuesView
A generic version of collections.abc.ValuesView.
__all__ = ['Annotated', 'Any', 'Callable', 'ClassVar', 'Concatenate', ...
FILE
c:\users\youse\appdata\local\programs\python\python312\lib\typing.py
tornado.version
Error rendering doc: No Python documentation found for '6.4.1'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
tornado.version_info
Python Library Documentation: tuple object class tuple(object) | tuple(iterable=(), /) | | Built-in immutable sequence. | | If no argument is given, the constructor returns an empty tuple. | If iterable is specified the tuple is initialized from iterable's items. | | If the argument is a tuple, the return value is the same object. | | Built-in subclasses: | asyncgen_hooks | UnraisableHookArgs | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return bool(key in self). | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(self, key, /) | Return self[key]. | | __getnewargs__(self, /) | | __gt__(self, value, /) | Return self>value. | | __hash__(self, /) | Return hash(self). | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value. | | __ne__(self, value, /) | Return self!=value. | | __repr__(self, /) | Return repr(self). | | __rmul__(self, value, /) | Return value*self. | | count(self, value, /) | Return number of occurrences of value. | | index(self, value, start=0, stop=9223372036854775807, /) | Return first index of value. | | Raises ValueError if the value is not present. | | ---------------------------------------------------------------------- | Class methods defined here: | | __class_getitem__(...) | See PEP 585 | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature.