本文整理匯總了Python中typing.Protocol方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.Protocol方法的具體用法?Python typing.Protocol怎麽用?Python typing.Protocol使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類typing
的用法示例。
在下文中一共展示了typing.Protocol方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: add_style_filter
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Protocol [as 別名]
def add_style_filter(self, style_filter: StyleFilterFunc) -> None:
"""Add a style filter function.
Args:
style_filter:
A function for filtering table cells, the function required to implement
the following Protocol:
.. code-block:: python
class StyleFilterFunc(Protocol):
def __call__(self, cell: Cell, **kwargs: Any) -> Optional[Style]:
...
"""
self._style_filters.insert(0, style_filter)
示例2: _get_protocol_attrs
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Protocol [as 別名]
def _get_protocol_attrs(cls):
attrs = set()
for base in cls.__mro__[:-1]: # without object
if base.__name__ in ('Protocol', 'Generic'):
continue
annotations = getattr(base, '__annotations__', {})
for attr in list(base.__dict__.keys()) + list(annotations.keys()):
if (not attr.startswith('_abc_') and attr not in (
'__abstractmethods__', '__annotations__', '__weakref__',
'_is_protocol', '_is_runtime_protocol', '__dict__',
'__args__', '__slots__',
'__next_in_mro__', '__parameters__', '__origin__',
'__orig_bases__', '__extra__', '__tree_hash__',
'__doc__', '__subclasshook__', '__init__', '__new__',
'__module__', '_MutableMapping__marker', '_gorg')):
attrs.add(attr)
return attrs
示例3: __class_getitem__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Protocol [as 別名]
def __class_getitem__(cls, params):
if not isinstance(params, tuple):
params = (params,)
if not params and cls is not Tuple:
raise TypeError(
"Parameter list to {}[...] cannot be empty".format(cls.__qualname__))
msg = "Parameters to generic types must be types."
params = tuple(_type_check(p, msg) for p in params)
if cls is Protocol:
# Generic can only be subscripted with unique type variables.
if not all(isinstance(p, TypeVar) for p in params):
i = 0
while isinstance(params[i], TypeVar):
i += 1
raise TypeError(
"Parameters to Protocol[...] must all be type variables."
" Parameter {} is {}".format(i + 1, params[i]))
if len(set(params)) != len(params):
raise TypeError(
"Parameters to Protocol[...] must all be unique")
else:
# Subscripting a regular Generic subclass.
_check_generic(cls, params)
return _GenericAlias(cls, params)
示例4: test_typing_guard_for_protocol
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Protocol [as 別名]
def test_typing_guard_for_protocol(self):
self.flakes("""
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Protocol
else:
Protocol = object
class C(Protocol):
def f(): # type: () -> int
pass
""")
示例5: test_new_repr_bare
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Protocol [as 別名]
def test_new_repr_bare(self):
T = TypeVar('T')
self.assertEqual(repr(Generic[T]), 'typing.Generic[~T]')
self.assertEqual(repr(typing._Protocol[T]), 'typing.Protocol[~T]')
class C(typing.Dict[Any, Any]): ...
# this line should just work
repr(C.__mro__)
示例6: check
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Protocol [as 別名]
def check(self, value, namespace):
# return isinstance(value, self._cls) # does not work for tg.Protocol
return issubclass(type(value), self._cls)
# Note: 'typing'-module checkers must register _before_ this one:
示例7: __getitem__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Protocol [as 別名]
def __getitem__(self, params):
# We also need to copy this from GenericMeta.__getitem__ to get
# special treatment of "Protocol". (Comments removed for brevity.)
if not isinstance(params, tuple):
params = (params,)
if not params and _gorg(self) is not Tuple:
raise TypeError(
"Parameter list to %s[...] cannot be empty" % self.__qualname__)
msg = "Parameters to generic types must be types."
params = tuple(_type_check(p, msg) for p in params)
if self in (Generic, Protocol):
if not all(isinstance(p, TypeVar) for p in params):
raise TypeError(
"Parameters to %r[...] must all be type variables" % self)
if len(set(params)) != len(params):
raise TypeError(
"Parameters to %r[...] must all be unique" % self)
tvars = params
args = params
elif self in (Tuple, Callable):
tvars = _type_vars(params)
args = params
elif self.__origin__ in (Generic, Protocol):
raise TypeError("Cannot subscript already-subscripted %s" %
repr(self))
else:
_check_generic(self, params)
tvars = _type_vars(params)
args = params
prepend = (self,) if self.__origin__ is None else ()
return self.__class__(self.__name__,
prepend + self.__bases__,
_no_slots_copy(self.__dict__),
tvars=tvars,
args=args,
origin=self,
extra=self.__extra__,
orig_bases=self.__orig_bases__)
示例8: __new__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Protocol [as 別名]
def __new__(cls, *args, **kwds):
if _gorg(cls) is Protocol:
raise TypeError("Type Protocol cannot be instantiated; "
"it can be used only as a base class")
if OLD_GENERICS:
return _generic_new(_next_in_mro(cls), cls, *args, **kwds)
return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
示例9: __init__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import Protocol [as 別名]
def __init__(cls, *args, **kwargs):
super().__init__(*args, **kwargs)
if not cls.__dict__.get('_is_protocol', None):
cls._is_protocol = any(b is Protocol or
isinstance(b, _ProtocolMeta) and
b.__origin__ is Protocol
for b in cls.__bases__)
if cls._is_protocol:
for base in cls.__mro__[1:]:
if not (base in (object, Generic) or
base.__module__ == 'collections.abc' and
base.__name__ in _PROTO_WHITELIST or
isinstance(base, TypingMeta) and base._is_protocol or
isinstance(base, GenericMeta) and
base.__origin__ is Generic):
raise TypeError('Protocols can only inherit from other'
' protocols, got %r' % base)
def _no_init(self, *args, **kwargs):
if type(self)._is_protocol:
raise TypeError('Protocols cannot be instantiated')
cls.__init__ = _no_init
def _proto_hook(other):
if not cls.__dict__.get('_is_protocol', None):
return NotImplemented
if not isinstance(other, type):
# Same error as for issubclass(1, int)
raise TypeError('issubclass() arg 1 must be a class')
for attr in _get_protocol_attrs(cls):
for base in other.__mro__:
if attr in base.__dict__:
if base.__dict__[attr] is None:
return NotImplemented
break
annotations = getattr(base, '__annotations__', {})
if (isinstance(annotations, typing.Mapping) and
attr in annotations and
isinstance(other, _ProtocolMeta) and
other._is_protocol):
break
else:
return NotImplemented
return True
if '__subclasshook__' not in cls.__dict__:
cls.__subclasshook__ = _proto_hook