Python typing.GenericMeta() Examples

The following are 28 code examples of typing.GenericMeta(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module typing , or try the search function .
Example #1
Source File: _typing.py    From pytablewriter with MIT License 6 votes vote down vote up
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 
Example #2
Source File: overloading.py    From overloading.py with MIT License 6 votes vote down vote up
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__ 
Example #3
Source File: typing_predicates.py    From typecheck-decorator with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example #4
Source File: test_six.py    From six with MIT License 6 votes vote down vote up
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],) 
Example #5
Source File: __init__.py    From pytypes with Apache License 2.0 5 votes vote down vote up
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 
Example #6
Source File: util.py    From container-pipeline-service with GNU General Public License v3.0 5 votes vote down vote up
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) 
Example #7
Source File: util.py    From anchore-engine with Apache License 2.0 5 votes vote down vote up
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) 
Example #8
Source File: util.py    From rbb_core with MIT License 5 votes vote down vote up
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) 
Example #9
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
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__) 
Example #10
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def __instancecheck__(self, instance):
            # We need this method for situations where attributes are
            # assigned in __init__.
            if ((not getattr(self, '_is_protocol', False) or
                    _is_callable_members_only(self)) and
                    issubclass(instance.__class__, self)):
                return True
            if self._is_protocol:
                if all(hasattr(instance, attr) and
                        (not callable(getattr(self, attr, None)) or
                         getattr(instance, attr) is not None)
                        for attr in _get_protocol_attrs(self)):
                    return True
            return super(GenericMeta, self).__instancecheck__(instance) 
Example #11
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def _next_in_mro(cls):  # noqa
        """This function exists for compatibility with old typing versions."""
        next_in_mro = object
        for i, c in enumerate(cls.__mro__[:-1]):
            if isinstance(c, GenericMeta) and _gorg(c) is Generic:
                next_in_mro = cls.__mro__[i + 1]
        return next_in_mro 
Example #12
Source File: _typing.py    From pytablewriter with MIT License 5 votes vote down vote up
def _gorg(cls):
    """This function exists for compatibility with old typing versions."""
    assert isinstance(cls, GenericMeta)
    if hasattr(cls, '_gorg'):
        return cls._gorg
    while cls.__origin__ is not None:
        cls = cls.__origin__
    return cls 
Example #13
Source File: helpers.py    From mashumaro with Apache License 2.0 5 votes vote down vote up
def is_generic(t):
    if PY_37 or PY_38:
        # noinspection PyProtectedMember
        # noinspection PyUnresolvedReferences
        return t.__class__ is typing._GenericAlias
    elif PY_36:
        # noinspection PyUnresolvedReferences
        return issubclass(t.__class__, typing.GenericMeta)
    else:
        raise NotImplementedError 
Example #14
Source File: framework.py    From typecheck-decorator with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _is_GenericMeta_class(annotation):
    return (inspect.isclass(annotation) and
            type(annotation) == tg.GenericMeta) 
Example #15
Source File: type_util.py    From pytypes with Apache License 2.0 5 votes vote down vote up
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 
Example #16
Source File: api_resource_metaclass.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
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] 
Example #17
Source File: test_typing.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
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)) 
Example #18
Source File: helpers.py    From pampy with MIT License 5 votes vote down vote up
def is_generic(pattern):
    return isinstance(pattern, GenericMeta) 
Example #19
Source File: test_compat_with_typing_Generic.py    From eth-utils with MIT License 5 votes vote down vote up
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") 
Example #20
Source File: overloading.py    From overloading.py with MIT License 5 votes vote down vote up
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 
Example #21
Source File: overloading.py    From overloading.py with MIT License 5 votes vote down vote up
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_) 
Example #22
Source File: facade.py    From python-libjuju with Apache License 2.0 5 votes vote down vote up
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 
Example #23
Source File: util.py    From articles with MIT License 5 votes vote down vote up
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) 
Example #24
Source File: util.py    From articles with MIT License 5 votes vote down vote up
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) 
Example #25
Source File: api_resource_metaclass.py    From codepost-python with GNU Lesser General Public License v3.0 5 votes vote down vote up
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

# ============================================================================= 
Example #26
Source File: _typing.py    From pytablewriter with MIT License 4 votes vote down vote up
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 
Example #27
Source File: config.py    From workload-collocation-agent with Apache License 2.0 4 votes vote down vote up
def assure_type(value, expected_type):
    """Should raise ValidationError based exception if value is not an instance of expected_type.
    """
    if expected_type == inspect.Parameter.empty:
        raise WeakValidationError('missing type declaration!')

    if isinstance(expected_type, typing.GenericMeta):
        if issubclass(expected_type, typing.List):
            _assure_list_type(value, expected_type)
            return

        elif issubclass(expected_type, typing.Dict):
            _assure_dict_type(value, expected_type)
            return

        else:
            # Warn about generic unhandled types (e.g. Iterable[int]), because:
            # "Parameterized generics cannot be used with class or instance checks" limitation.
            raise WeakValidationError('generic type found %r' % expected_type)

    # Handle union type.
    if isinstance(expected_type, typing.Union.__class__):
        _assure_union_type(value, expected_type)
        return

    # Handle union type.
    if isinstance(expected_type, enum.Enum.__class__):
        _assure_enum_type(value, expected_type)
        return

    # Handle Semantic type.
    if isinstance(expected_type, types.FunctionType):
        expected_type = expected_type()

    if issubclass(expected_type, SemanticType):
        expected_type.assure(value)
        return

    # Handle simple types.
    if not isinstance(value, expected_type):
        raise ValidationError(
            'improper type (got=%r expected=%r)!' % (type(value), expected_type)) 
Example #28
Source File: api_resource_metaclass.py    From codepost-python with GNU Lesser General Public License v3.0 4 votes vote down vote up
def _build_signature(
        cls,
        obj,
        with_fields=True,
        with_id=True,
        with_self=True,
        all_optional=False):

        parameters = []

        if with_self:
            parameters.append(_forge.arg("self"))

        if with_id:
            parameters.append(_forge.arg(obj._FIELD_ID, type=int))

        if with_fields:

            # Recompute FIELDS object

            fields = obj._FIELDS

            if isinstance(fields, list):
                fields = { key: str for key in fields }

            if isinstance(fields, dict):
                # The default format is (type, default_value).
                # This code tries to expand 'type' -> (type, "")
                # Since some of the type hints can be abstract, like typing.List[int], it has
                # to use the GenericAlias/GenericMeta code
                # see code in:
                # https://github.com/codepost-io/codepost-python/commit/2b0ae00d160ddae0b6540b32bfb2778f428dccd7#diff-b7cc0946b625e77d99cb9a61818cd773R44-R71

                # There are two possibilities:
                # 1) (typ, default_value): a default value is provided -> use it
                # 2) typ: no default value is provided -> use "" instead

                fields = {
                    key: (val, "") if is_type_variable(val)
                    else val
                    for (key, val) in fields.items()
                }

            # Create forge parameters

            for (key, val) in fields.items():
                if key in obj._FIELDS_READ_ONLY:
                    continue

                if all_optional or not key in obj._FIELDS_REQUIRED:
                    parameters.append(
                        _forge.arg(key, type=val[0], default=_FORGE_VOID))
                else:
                    parameters.append(
                        _forge.arg(key, type=val[0]))

        return _forge.FSignature(parameters=parameters)