语法语句
def _tp_cache(func=None, , *, typed=False):"""Internal wrapper caching __getitem__ of generic types with a fallback tooriginal function for non-hashable arguments."""def decorator(func):cached = functools.lru_cache(typed=typed)(func)_cleanups.append(cached.cache_clear)@functools.wraps(func)def inner(*args, **kwds):try:return cached(*args, **kwds)except TypeError:pass # All real errors (not unhashable args) are raised below.return func(*args, **kwds)return innerif func is not None:return decorator(func)return decoratorclass _Final:"""Mixin to prohibit subclassing"""__slots__ = ('__weakref__',)def __init_subclass__(self, , *args, **kwds):if '_root' not in kwds:raise TypeError("Cannot subclass special typing classes")class _SpecialForm(_Final, _root=True):__slots__ = ('_name', '__doc__', '_getitem')def __init__(self, getitem):self._getitem = getitemself._name = getitem.__name__self.__doc__ = getitem.__doc__def __mro_entries__(self, bases):raise TypeError(f"Cannot subclass {self!r}")def __repr__(self):return 'typing.' + self._namedef __reduce__(self):return self._namedef __call__(self, *args, **kwds):raise TypeError(f"Cannot instantiate {self!r}")def __instancecheck__(self, obj):raise TypeError(f"{self} cannot be used with isinstance()")def __subclasscheck__(self, cls):raise TypeError(f"{self} cannot be used with issubclass()")@_tp_cachedef __getitem__(self, parameters):return self._getitem(self, parameters)
@_SpecialFormdef Final(self, parameters):"""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 = 9000MAX_SIZE += 1 # Error reported by type checkerclass Connection:TIMEOUT: Final[int] = 10class FastConnector(Connection):TIMEOUT = 1 # Error reported by type checkerThere is no runtime checking of these properties."""item = _type_check(parameters, f'{self} accepts only single type.')return _GenericAlias(self, (item,))
常用类型注释
Any:任何类型
NoReturn:函数无返回值的类型
ClassVar:类属性类型
Final:不可变变量类型
Union:联合类型,起或的作用
Optional:可None的类型,只支持一种类型
Literal:可选的几个值
TypeVar:自定义类型,可结合多个类型
Callable:可调用的变量类型,比如函数
Tuple:元组,固定长度不同类型元素|可变长度的同一类型|可变长度的不同类型
List:列表,同一类型|不同类型
Dict:字典,key-value
特殊类型注释
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 recognizestructural subtyping (static duck-typing), for example::class C:def meth(self) -> int:return 0def func(x: Proto) -> int:return x.meth()func(C()) # Passes static type check
A generic type is typically declared by inheriting fromthis class parameterized with one or more type variables.For example, a generic mapping type might be defined as::class Mapping(Generic[KT, VT]):def __getitem__(self, key: KT) -> VT:...# Etc.This class can then be used as follows::def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:try:return mapping[key]except KeyError:return default
文章转载自与C同行,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




