Ejemplo n.º 1
0
def test_generic_alias(_multidict) -> None:

    assert _multidict.MultiDict[int] == types.GenericAlias(
        _multidict.MultiDict, (int, ))
    assert _multidict.MultiDictProxy[int] == types.GenericAlias(
        _multidict.MultiDictProxy, (int, ))
    assert _multidict.CIMultiDict[int] == types.GenericAlias(
        _multidict.CIMultiDict, (int, ))
    assert _multidict.CIMultiDictProxy[int] == types.GenericAlias(
        _multidict.CIMultiDictProxy, (int, ))
Ejemplo n.º 2
0
 def test_exposed_type(self):
     import types
     a = types.GenericAlias(list, int)
     self.assertEqual(str(a), 'list[int]')
     self.assertIs(a.__origin__, list)
     self.assertEqual(a.__args__, (int, ))
     self.assertEqual(a.__parameters__, ())
Ejemplo n.º 3
0
    def _resolve_type_hint(context_type: type, resolve_type: type) -> type:
        if not hasattr(types, 'GenericAlias') or not isinstance(
                resolve_type, types.GenericAlias):
            return resolve_type

        args = tuple(
            _resolve_type(context_type, arg) for arg in resolve_type.__args__)
        return types.GenericAlias(resolve_type.__origin__, args)
Ejemplo n.º 4
0
def of_complex_type(t: type) -> Predicate[object]:
    # Hack to support PEP 604 before it's implemented in typeguard, tracking issue for
    # that feature is here: https://github.com/agronholm/typeguard/issues/222
    # Rewrite types.UnionType objects generated by PEP 604 unions as types.GenericAlias,
    # as if it was generated by a Union[].
    t = (
        types.GenericAlias(Union, get_args(t))  # type: ignore
        if is_union_type(t) else t)

    @bind_name(of_complex_type, t)
    def check(a: object) -> bool:
        try:
            typeguard.check_type("a", a, t, globals={}, locals={})
        except TypeError:
            return False
        return True

    return check
Ejemplo n.º 5
0
import pickle
import weakref
from typing import TypeVar, Any, Union, Callable

import pytest
import numpy as np
from numpy.typing._generic_alias import _GenericAlias

ScalarType = TypeVar("ScalarType", bound=np.generic, covariant=True)
T1 = TypeVar("T1")
T2 = TypeVar("T2")
DType = _GenericAlias(np.dtype, (ScalarType, ))
NDArray = _GenericAlias(np.ndarray, (Any, DType))

if sys.version_info >= (3, 9):
    DType_ref = types.GenericAlias(np.dtype, (ScalarType, ))
    NDArray_ref = types.GenericAlias(np.ndarray, (Any, DType_ref))
    FuncType = Callable[[Union[_GenericAlias, types.GenericAlias]], Any]
else:
    DType_ref = Any
    NDArray_ref = Any
    FuncType = Callable[[_GenericAlias], Any]

GETATTR_NAMES = sorted(set(dir(np.ndarray)) - _GenericAlias._ATTR_EXCEPTIONS)

BUFFER = np.array([1], dtype=np.int64)
BUFFER.setflags(write=False)


def _get_subclass_mro(base: type) -> tuple[type, ...]:
    class Subclass(base):  # type: ignore[misc,valid-type]
Ejemplo n.º 6
0
 def __getitem__(self, key):
     return types.GenericAlias(self, key)
        "__copy__",
        "__deepcopy__",
    })

    def __getattribute__(self, name: str) -> Any:
        """Return ``getattr(self, name)``."""
        # Pull the attribute from `__origin__` unless its
        # name is in `_ATTR_EXCEPTIONS`
        cls = type(self)
        if name in cls._ATTR_EXCEPTIONS:
            return super().__getattribute__(name)
        return getattr(self.__origin__, name)


# See `_GenericAlias.__eq__`
if sys.version_info >= (3, 9):
    _GENERIC_ALIAS_TYPE = (_GenericAlias, types.GenericAlias)
else:
    _GENERIC_ALIAS_TYPE = (_GenericAlias, )

ScalarType = TypeVar("ScalarType", bound=np.generic, covariant=True)

if TYPE_CHECKING:
    NDArray = np.ndarray[Any, np.dtype[ScalarType]]
elif sys.version_info >= (3, 9):
    _DType = types.GenericAlias(np.dtype, (ScalarType, ))
    NDArray = types.GenericAlias(np.ndarray, (Any, _DType))
else:
    _DType = _GenericAlias(np.dtype, (ScalarType, ))
    NDArray = _GenericAlias(np.ndarray, (Any, _DType))
Ejemplo n.º 8
0
 def __class_getitem__(self, item):
     return types.GenericAlias(self, item)