本文整理匯總了Python中typing.GenericMeta方法的典型用法代碼示例。如果您正苦於以下問題:Python typing.GenericMeta方法的具體用法?Python typing.GenericMeta怎麽用?Python typing.GenericMeta使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類typing
的用法示例。
在下文中一共展示了typing.GenericMeta方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: iter_generic_bases
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def iter_generic_bases(type_):
"""Iterates over all generics `type_` derives from, including origins.
This function is only necessary because, in typing 3.5.0, a generic doesn't
get included in the list of bases when it constructs a parameterized version
of itself. This was fixed in aab2c59; now it would be enough to just iterate
over the MRO.
"""
for t in type_.__mro__:
if not isinstance(t, typing.GenericMeta):
continue
yield t
t = t.__origin__
while t:
yield t
t = t.__origin__
示例2: test_with_metaclass_typing
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def test_with_metaclass_typing():
try:
import typing
except ImportError:
pytest.skip("typing module required")
class Meta(type):
pass
if sys.version_info[:2] < (3, 7):
# Generics with custom metaclasses were broken on older versions.
class Meta(Meta, typing.GenericMeta):
pass
T = typing.TypeVar('T')
class G(six.with_metaclass(Meta, typing.Generic[T])):
pass
class GA(six.with_metaclass(abc.ABCMeta, typing.Generic[T])):
pass
assert isinstance(G, Meta)
assert isinstance(GA, abc.ABCMeta)
assert G[int] is not G[G[int]]
assert GA[int] is not GA[GA[int]]
assert G.__bases__ == (typing.Generic,)
assert G.__orig_bases__ == (typing.Generic[T],)
示例3: check
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def check(self, value, namespace):
if not self._is_possible_subclass(type(value), self._cls):
return False # totally the wrong type
# now check the content of the value, if possible:
assert type(self._cls) == tg.GenericMeta
params = self._cls.__parameters__
result = True # any failing check will set it to False
# check checkable relevant properties of all
# relevant Generic subclasses from the typing module.
# Fall back from specific to less specific leave the content
# check out if there are more __parameters__ than expected:
if (self._we_want_to_check(value, tg.Sequence)):
return self._check_sequence(value, params, namespace)
if (self._we_want_to_check(value, tg.Mapping)):
return self._check_mapping(value, params, namespace)
if (self._we_want_to_check(value, tg.Iterable)):
return self._check_by_iterator(value, params, namespace)
# tg.Iterator: nothing is checkable: reading would modify it
# tg.Container: nothing is checkable: would need to guess elements
return True # no content checking possible
示例4: __subclasscheck__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def __subclasscheck__(self, subclass):
"""This mimics a more modern GenericMeta.__subclasscheck__() logic
(that does not have problems with recursion) to work around interactions
between collections, typing, and typing_extensions on older
versions of Python, see https://github.com/python/typing/issues/501.
"""
if sys.version_info[:3] >= (3, 5, 3) or sys.version_info[:3] < (3, 5, 0):
if self.__origin__ is not None:
if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
raise TypeError("Parameterized generics cannot be used with class "
"or instance checks")
return False
if not self.__extra__:
return super().__subclasscheck__(subclass)
res = self.__extra__.__subclasshook__(subclass)
if res is not NotImplemented:
return res
if self.__extra__ in subclass.__mro__:
return True
for scls in self.__extra__.__subclasses__():
if isinstance(scls, GenericMeta):
continue
if issubclass(subclass, scls):
return True
return False
示例5: detect_list_type
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def detect_list_type(typ):
"""
Internal method to detect whether an abstract type is a List-type, and if so
returns the type of the list elements. Returns `None` otherwise.
:param field_type: The abstract type to be analyzed.
:return: The type of the list elements, or `None`.
"""
# Read more about this issue here:
# https://github.com/swagger-api/swagger-codegen/issues/8921
if _sys.version_info >= (3, 7):
if type(typ) is _typing._GenericAlias and typ._name == "List":
return typ.__args__[0]
elif _sys.version_info >= (3, 0):
try:
if (type(typ) is _typing.GenericMeta and
(hasattr(typ, "__extra__") and typ.__extra__ is list)):
return typ.__args__[0]
except AttributeError:
pass
if hasattr(typ, "__origin__") and typ.__origin__ is _typing.List:
return typ.__args__[0]
示例6: is_type_variable
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def is_type_variable(typ):
"""
Determines whether an object is a type variable.
:param typ: The variable to be analyzed.
:return: `True` if variable is either an elementary type or an abstract type.
"""
# All elementary types are simple
if type(typ) is type:
return True
# Now we must handle "abstract" types (i.e., List[int] for instance)
# NOTE: Since our framework only uses List[xxx] we can limit to this subcase
# for the moment (avoid unpredictability).
_only_allow_list_generic_objects = True
if _sys.version_info >= (3, 7):
return type(typ) is _typing._GenericAlias and (
not _only_allow_list_generic_objects or
typ._name == "List")
elif _sys.version_info >= (3, 0):
try:
return type(typ) is _typing.GenericMeta and (
not _only_allow_list_generic_objects or
(hasattr(typ, "__extra__") and typ.__extra__ is list)
)
except AttributeError:
pass
return hasattr(typ, "__origin__") and (
not _only_allow_list_generic_objects or
typ.__origin__ is _typing.List
)
# default case is that `typ` is probably not a type reference
return False
# =============================================================================
示例7: _deserialize
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def _deserialize(data, klass):
"""Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object.
"""
if data is None:
return None
if klass in six.integer_types or klass in (float, str, bool):
return _deserialize_primitive(data, klass)
elif klass == object:
return _deserialize_object(data)
elif klass == datetime.date:
return deserialize_date(data)
elif klass == datetime.datetime:
return deserialize_datetime(data)
elif type(klass) == typing.GenericMeta:
if klass.__extra__ == list:
return _deserialize_list(data, klass.__args__[0])
if klass.__extra__ == dict:
return _deserialize_dict(data, klass.__args__[1])
else:
return deserialize_model(data, klass)
示例8: strcast
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def strcast(kind, keep_builtins=False):
if (kind in basic_types or
type(kind) in basic_types) and keep_builtins is False:
return kind.__name__
if str(kind).startswith('~'):
return str(kind)[1:]
if kind is typing.Any:
return 'Any'
try:
if issubclass(kind, typing.GenericMeta):
return str(kind)[1:]
except AttributeError:
pass
return kind
示例9: normalize_type
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def normalize_type(type_, level=0):
"""
Reduces an arbitrarily complex type declaration into something manageable.
"""
if not typing or not isinstance(type_, typing.TypingMeta) or type_ is AnyType:
return type_
if isinstance(type_, typing.TypeVar):
if type_.__constraints__ or type_.__bound__:
return type_
else:
return AnyType
if issubclass(type_, typing.Union):
if not type_.__union_params__:
raise OverloadingError("typing.Union must be parameterized")
return typing.Union[tuple(normalize_type(t, level) for t in type_.__union_params__)]
if issubclass(type_, typing.Tuple):
params = type_.__tuple_params__
if level > 0 or params is None:
return typing.Tuple
elif type_.__tuple_use_ellipsis__:
return typing.Tuple[normalize_type(params[0], level + 1), ...]
else:
return typing.Tuple[tuple(normalize_type(t, level + 1) for t in params)]
if issubclass(type_, typing.Callable):
return typing.Callable
if isinstance(type_, typing.GenericMeta):
base = find_base_generic(type_)
if base is typing.Generic:
return type_
else:
return GenericWrapper(type_, base, level > 0)
raise OverloadingError("%r not supported yet" % type_)
示例10: __eq__
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def __eq__(cls, other):
if isinstance(other, GenericWrapperMeta):
return cls.type == other.type
elif isinstance(other, typing.GenericMeta):
return cls.type == other
else:
return False
示例11: test_has_logger_compat_with_typing_Generic
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def test_has_logger_compat_with_typing_Generic():
from typing import GenericMeta
class HasLoggerCompatWithGeneric(metaclass=HasLoggerMeta.meta_compat(GenericMeta)):
...
assert hasattr(HasLoggerCompatWithGeneric, "logger")
assert isinstance(HasLoggerCompatWithGeneric.logger, logging.Logger)
assert HasLoggerCompatWithGeneric.logger.name.endswith("HasLoggerCompatWithGeneric")
示例12: is_generic
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def is_generic(pattern):
return isinstance(pattern, GenericMeta)
示例13: test_subscript_meta
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def test_subscript_meta(self):
T = TypeVar('T')
self.assertEqual(Type[GenericMeta], Type[GenericMeta])
self.assertEqual(Union[T, int][GenericMeta], Union[GenericMeta, int])
self.assertEqual(Callable[..., GenericMeta].__args__, (Ellipsis, GenericMeta))
示例14: _GenericMeta__new__351
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def _GenericMeta__new__351(cls, *args, **kwds):
origin = None
if len(args) >= 6:
# origin is at index 5 in original signature:
# name, bases, namespace, tvars=None, args=None, origin=None, extra=None, orig_bases=None
origin = args[5]
elif 'origin' in kwds:
origin = kwds['origin']
res = _GenericMeta__new__(cls, *args, **kwds)
# we correct the hash according to the fix in https://github.com/python/typing/pull/371
res.__tree_hash__ = (hash(res._subs_tree()) if origin else
super(typing.GenericMeta, res).__hash__())
return res
示例15: is_Generic
# 需要導入模塊: import typing [as 別名]
# 或者: from typing import GenericMeta [as 別名]
def is_Generic(tp):
try:
return isinstance(tp, typing.GenericMeta)
except AttributeError:
try:
return issubclass(tp, typing.Generic)
# return isinstance(tp, typing._VariadicGenericAlias) and \
# tp.__origin__ is tuple
except AttributeError:
return False
except TypeError:
# Shall we accept _GenericAlias, i.e. Tuple, Union, etc?
return isinstance(tp, typing._GenericAlias)
#return False