当前位置: 首页>>代码示例>>Python>>正文


Python typing.GenericMeta方法代码示例

本文整理汇总了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__ 
开发者ID:bintoro,项目名称:overloading.py,代码行数:18,代码来源:overloading.py

示例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],) 
开发者ID:benjaminp,项目名称:six,代码行数:24,代码来源:test_six.py

示例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 
开发者ID:prechelt,项目名称:typecheck-decorator,代码行数:22,代码来源:typing_predicates.py

示例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 
开发者ID:thombashi,项目名称:pytablewriter,代码行数:27,代码来源:_typing.py

示例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] 
开发者ID:codepost-io,项目名称:codepost-python,代码行数:28,代码来源:api_resource_metaclass.py

示例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

# ============================================================================= 
开发者ID:codepost-io,项目名称:codepost-python,代码行数:43,代码来源:api_resource_metaclass.py

示例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) 
开发者ID:hmajid2301,项目名称:articles,代码行数:28,代码来源:util.py

示例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 
开发者ID:juju,项目名称:python-libjuju,代码行数:16,代码来源:facade.py

示例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_) 
开发者ID:bintoro,项目名称:overloading.py,代码行数:34,代码来源:overloading.py

示例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 
开发者ID:bintoro,项目名称:overloading.py,代码行数:9,代码来源:overloading.py

示例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") 
开发者ID:ethereum,项目名称:eth-utils,代码行数:11,代码来源:test_compat_with_typing_Generic.py

示例12: is_generic

# 需要导入模块: import typing [as 别名]
# 或者: from typing import GenericMeta [as 别名]
def is_generic(pattern):
    return isinstance(pattern, GenericMeta) 
开发者ID:santinic,项目名称:pampy,代码行数:4,代码来源:helpers.py

示例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)) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:7,代码来源:test_typing.py

示例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 
开发者ID:Stewori,项目名称:pytypes,代码行数:15,代码来源:__init__.py

示例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 
开发者ID:Stewori,项目名称:pytypes,代码行数:16,代码来源:type_util.py


注:本文中的typing.GenericMeta方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。