python新特性详解及版本
— Support for type hints¶
New in version 3.5.
Note
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 as specified by PEP 484, PEP 526, PEP 544, PEP 586, PEP 589, and PEP 591. The most fundamental support consists of the typesAny,Union,Tuple,Callable,TypeVar, andGeneric. For full specification please seePEP 484. For a simplified introduction to type hints see PEP 483.
The function below takes and returns a string and is annotated as follows:
defgreeting(name: str) ->str:
return'Hello '+name
In the functiongreeting, the argumentnameis expected to be of typestrand the return typestr. Subtypes are accepted as arguments.
SeePEP 484 for more details.
Note
Recall that the use of a type alias declares two types to be equivalent to one another. DoingAlias =Originalwill make the static type checker treatAliasas being exactly equivalent toOriginalin all cases. This is useful when you want to simplify complex type signatures.
In contrast,NewTypedeclares one type to be a subtype of another. DoingDerived = NewType('Derived',Original)will make the static type checker treatDerivedas a subclass ofOriginal, which means a value of typeOriginalcannot be used in places where a value of typeDerivedis expected. This is useful when you want to prevent logic errors with minimal runtime cost.
New in version 3.5.2.
Callable
Frameworks expecting callback functions of specific signatures might be type hinted usingCallable[[Arg1Type,Arg2Type], ReturnType].
For example:
fromtypingimportCallable
deffeeder(get_next_item: Callable[[], str]) ->None:
# Body
defasync_query(on_success: Callable[[int], None],
on_error: Callable[[int, Exception], None]) ->None:
# Body
It is possible to declare the return type of a callable without specifying the call signature by substituting a literal ellipsis for the list of arguments in the type hint:Callable[..., ReturnType].
Generics
Since type information about objects kept in containers cannot be statically inferred in a generic way, abstract base classes have been extended to support subscription to denote expected types for container elements.
fromtypingimportMapping, Sequence
defnotify_by_email(employees: Sequence[Employee],
overrides: Mapping[str, str]) ->None: ...
Generics can be parameterized by using a new factory available in typing calledTypeVar.
InitiallyPEP 484 defined Python static type system as using nominal subtyping. This means that a class Ais allowed where a classBis expected if and only ifAis a subclass ofB.
fromtypingimportSized, Iterable, Iterator
classBucket(Sized, Iterable[int]):
...
def__len__(self) ->int: ...
def__iter__(self) ->Iterator[int]: ...
PEP 544allows to solve this problem by allowing users to write the above code without explicit base classes in the class definition, allowingBucketto be implicitly considered a subtype of bothSizedandIterable[int]by static type checkers. This is known as structural subtyping (or static duck-typing):
fromtypingimportIterator, Iterable
classBucket: # Note: no base classes
...
def__len__(self) ->int: ...
def__iter__(self) ->Iterator[int]: ...
defcollect(items: Iterable[int]) ->int: ...
result =collect(Bucket()) # Passes type check
Type variables may be marked covariant or contravariant by passingcovariant=Trueorcontravariant=True. SeePEP 484 for more details. By default type variables are invariant. Alternatively, a type variable may specify an upper bound using bound=. This means that an actual type substituted (explicitly or implicitly) for the type variable must be a subclass of the boundary type, see PEP 484.
classtyping.Generic
Abstract base class for generic types.
A generic type is typically declared by inheriting from an instantiation of this class with one or more type variables. For example, a generic mapping type might be defined as:
classMapping(Generic[KT, VT]):
def__getitem__(self, key: KT) ->VT:
...
# Etc.
This class can then be used as follows:
X =TypeVar('X')
Y =TypeVar('Y')
deflookup_name(mapping: Mapping[X, Y], key: X, default: Y) ->Y:
try:
returnmapping[key]
exceptKeyError:
returndefault
classtyping.Protocol(Generic)
Base class for protocol classes. Protocol classes are defined like this:
classProto(Protocol):
defmeth(self) ->int:
...
Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:
classC:
defmeth(self) ->int:
return0
deffunc(x: Proto) ->int:
returnx.meth()
func(C()) # Passes static type check
The only legal parameters forTypeare classes,Any,type variables, and unions of any of these types. For example:
defnew_non_team_user(user_class: Type[Union[BaseUser, ProUser]]): ...
Type[Any]is equivalent toTypewhich in turn is equivalent totype, which is the root of Python's metaclass hierarchy.
New in version 3.5.2.
classtyping.Iterable(Generic[T_co])
Changed in version 3.6.1:Added support for default values, methods, and docstrings.
Deprecated since version 3.8, will be removed in version 3.9:Deprecated the_field_typesattribute in favor of the more standard__annotations__attribute which has the same information.
Changed in version 3.8:The_field_typesand__annotations__attributes are now regular dictionaries instead of instances ofOrderedDict.
classtyping.TypedDict(dict)
A simple typed namespace. At runtime it is equivalent to a plaindict.
Point2D =TypedDict('Point2D', x=int, y=int, label=str)
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. Usage:
classpoint2D(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.
See PEP 589 for more examples and detailed rules of usingTypedDict.
New in version 3.8.
classtyping.ForwardRef
A class used for internal typing representation of string forward references. For example,List["SomeClass"]is implicitly transformed intoList[ForwardRef("SomeClass")]. This class should not be instantiated by a user, but may be used by introspection tools.
typing.NewType(name,tp)
A helper function to indicate a distinct type to a typechecker, see NewType. At runtime it returns a function that returns its argument. Usage:
UserId =NewType('UserId', int)
first_user =UserId(1)
New in version 3.5.2.
typing.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).
typing.get_type_hints(obj[,globals[,locals]])
Return a dictionary containing type hints for a function, method, module or class object.
This is often the same asobj.__annotations__. In addition, forward references encoded as string literals are handled by evaluating them inglobalsandlocalsnamespaces. If necessary,Optional[t]is added for function and method annotations if a default value equal toNoneis set. For a classC, return a dictionary constructed by merging all the__annotations__alongC.__mro__in reverse order.
typing.get_origin(tp)
typing.get_args(tp)
Provide basic introspection for generic types and special typing forms.
SeePEP 484 for details and comparison with other typing semantics.
@typing.final
A decorator to indicate to type checkers that the decorated method cannot be overridden, and the decorated class cannot be subclassed. For example:
classBase:
@final
defdone(self) ->None:
...
classSub(Base):
defdone(self) ->None: # Error reported by type checker
...
@final
classLeaf:
...
classOther(Leaf): # Error reported by type checker
...
There is no runtime checking of these properties. See PEP 591 for more details.
New in version 3.8.
@typing.no_type_check
Decorator to indicate that annotations are not type hints.
This works as class or function decorator. With a class, it applies recursively to all methods defined in that class (but not to methods defined in its superclasses or subclasses).
This mutates the function(s) in place.
@typing.no_type_check_decorator
Decorator to give another decorator theno_type_check()effect.
Anyis compatible with every type.
typing.NoReturn
Special type indicating that a function never returns. For example:
fromtypingimportNoReturn
defstop() ->NoReturn:
raiseRuntimeError('no way')
New in version 3.5.4.
New in version 3.6.2.
typing.Union
Union type;Union[X, Y]means either X or Y.
To define a union, use e.g.Union[int, str]. Details:
The arguments must be types and there must be at least one.
Unions of unions are flattened, e.g.:
Union[Union[int, str], float] ==Union[int, str, float]
Unions of a single argument vanish, e.g.:
Union[int] ==int# The constructor actually returns int
Redundant arguments are skipped, e.g.:
Union[int, str, int] ==Union[int, str]
When comparing unions, the argument order is ignored, e.g.:
Union[int, str] ==Union[str, int]
You cannot subclass or instantiate a union.
You cannot writeUnion[X][Y].
You can useOptional[X]as a shorthand forUnion[X, None].
Changed in version 3.7:Don't remove explicit subclasses from unions at runtime.
typing.Optional
Optional type.
Optional[X]is equivalent toUnion[X, None].
Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require theOptionalqualifier on its type annotation just because it is optional. For example:
deffoo(arg: int=0) ->None:
...
On the other hand, if an explicit value ofNoneis allowed, the use ofOptionalis appropriate, whether the argument is optional or not. For example:
deffoo(arg: Optional[int] =None) ->None:
...
typing.Tuple
Tuple type;Tuple[X, Y]is the type of a tuple of two items with the first item of type X and the second of type Y. The type of the empty tuple can be written asTuple[()].
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 literal ellipsis, e.g.Tuple[int, ...]. A plainTupleis equivalent toTuple[Any, ...], and in turn totuple.
New in version 3.8.
typing.ClassVar
Special type construct to mark class variables.
As introduced in PEP 526, a variable 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:
classStarship:
stats: ClassVar[Dict[str, int]] ={} # class variable
damage: int=10# instance variable
ClassVaraccepts only types and cannot be further subscribed.
New in version 3.8.
typing.AnyStr
AnyStris a type variable defined asAnyStr = TypeVar('AnyStr', str, bytes).
It is meant to be used for functions that may accept any kind of string without allowing different kinds of strings to mix. For example:
defconcat(a: AnyStr, b: AnyStr) ->AnyStr:
returna +b
concat(u"foo", u"bar") # Ok, output has type 'unicode'
concat(b"foo", b"bar") # Ok, output has type 'bytes'
concat(u"foo", b"bar") # Error, cannot mix unicode and bytes
typing.TYPE_CHECKING
A special constant that is assumed to beTrueby 3rd party static type checkers. It isFalseat runtime. Usage:
ifTYPE_CHECKING:
importexpensive_mod
deffun(arg: 'expensive_mod.SomeType') ->None:
local_var: expensive_mod.AnotherType =other_fun()
Note that the first type annotation must be enclosed in quotes, making it a "forward reference", to hide theexpensive_modreference from the interpreter runtime. Type annotations for local variables are not evaluated, so the second annotation does not need to be enclosed in quotes.
New in version 3.5.2.