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


Python typing.Generic方法代码示例

本文整理汇总了Python中typing.Generic方法的典型用法代码示例。如果您正苦于以下问题:Python typing.Generic方法的具体用法?Python typing.Generic怎么用?Python typing.Generic使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在typing的用法示例。


在下文中一共展示了typing.Generic方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_generic_extending

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def test_generic_extending(self):
        S = TypeVar('S')
        T = TypeVar('T')

        @dataclass
        class Base(Generic[T, S]):
            x: T
            y: S

        @dataclass
        class DataDerived(Base[int, T]):
            new_field: str
        Alias = DataDerived[str]
        c = Alias(0, 'test1', 'test2')
        self.assertEqual(astuple(c), (0, 'test1', 'test2'))

        class NonDataDerived(Base[int, T]):
            def new_method(self):
                return self.y
        Alias = NonDataDerived[float]
        c = Alias(10, 1.0)
        self.assertEqual(c.new_method(), 1.0) 
开发者ID:ericvsmith,项目名称:dataclasses,代码行数:24,代码来源:test_dataclasses.py

示例2: test_generic_dynamic

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def test_generic_dynamic(self):
        T = TypeVar('T')

        @dataclass
        class Parent(Generic[T]):
            x: T
        Child = make_dataclass('Child', [('y', T), ('z', Optional[T], None)],
                               bases=(Parent[int], Generic[T]), namespace={'other': 42})
        self.assertIs(Child[int](1, 2).z, None)
        self.assertEqual(Child[int](1, 2, 3).z, 3)
        self.assertEqual(Child[int](1, 2, 3).other, 42)
        # Check that type aliases work correctly.
        Alias = Child[T]
        self.assertEqual(Alias[int](1, 2).x, 1)
        # Check MRO resolution.
        self.assertEqual(Child.__mro__, (Child, Parent, Generic, object)) 
开发者ID:ericvsmith,项目名称:dataclasses,代码行数:18,代码来源:test_dataclasses.py

示例3: test_any_is_subclass

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def test_any_is_subclass(self):
        # Any should be considered a subclass of everything.
        assert issubclass(Any, Any)
        assert issubclass(Any, typing.List)
        assert issubclass(Any, typing.List[int])
        assert issubclass(Any, typing.List[T])
        assert issubclass(Any, typing.Mapping)
        assert issubclass(Any, typing.Mapping[str, int])
        assert issubclass(Any, typing.Mapping[KT, VT])
        assert issubclass(Any, Generic)
        assert issubclass(Any, Generic[T])
        assert issubclass(Any, Generic[KT, VT])
        assert issubclass(Any, AnyStr)
        assert issubclass(Any, Union)
        assert issubclass(Any, Union[int, str])
        assert issubclass(Any, typing.Match)
        assert issubclass(Any, typing.Match[str])
        # These expressions must simply not fail.
        typing.Match[Any]
        typing.Pattern[Any]
        typing.IO[Any] 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:23,代码来源:test_typing.py

示例4: test_pickle

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def test_pickle(self):
        T = TypeVar('T')
        class B(Generic[T]):
            pass
        global C  # pickle wants to reference the class by name
        class C(B[int]):
            pass
        c = C()
        c.foo = 42
        c.bar = 'abc'
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            z = pickle.dumps(c, proto)
            x = pickle.loads(z)
            self.assertEqual(x.foo, 42)
            self.assertEqual(x.bar, 'abc')
            self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'}) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:18,代码来源:test_typing.py

示例5: test_type_erasure

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def test_type_erasure(self):
        T = TypeVar('T')

        class Node(Generic[T]):
            def __init__(self, label: T,
                         left: 'Node[T]' = None,
                         right: 'Node[T]' = None):
                self.label = label  # type: T
                self.left = left  # type: Optional[Node[T]]
                self.right = right  # type: Optional[Node[T]]

        def foo(x: T):
            a = Node(x)
            b = Node[T](x)
            c = Node[Any](x)
            assert type(a) is Node
            assert type(b) is Node
            assert type(c) is Node

        foo(42) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:22,代码来源:test_typing.py

示例6: test_with_metaclass_typing

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [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

示例7: test_generic_errors

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def test_generic_errors(self):
        T = TypeVar('T')
        S = TypeVar('S')
        with self.assertRaises(TypeError):
            Generic[T]()
        with self.assertRaises(TypeError):
            Generic[T][T]
        with self.assertRaises(TypeError):
            Generic[T][S]
        with self.assertRaises(TypeError):
            isinstance([], List[int])
        with self.assertRaises(TypeError):
            issubclass(list, List[int])
        with self.assertRaises(TypeError):
            class NewGeneric(Generic): ...
        with self.assertRaises(TypeError):
            class MyGeneric(Generic[T], Generic[S]): ...
        with self.assertRaises(TypeError):
            class MyGeneric(List[T], Generic[S]): ... 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:21,代码来源:test_typing.py

示例8: test_chain_repr

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def test_chain_repr(self):
        T = TypeVar('T')
        S = TypeVar('S')

        class C(Generic[T]):
            pass

        X = C[Tuple[S, T]]
        self.assertEqual(X, C[Tuple[S, T]])
        self.assertNotEqual(X, C[Tuple[T, S]])

        Y = X[T, int]
        self.assertEqual(Y, X[T, int])
        self.assertNotEqual(Y, X[S, int])
        self.assertNotEqual(Y, X[T, str])

        Z = Y[str]
        self.assertEqual(Z, Y[str])
        self.assertNotEqual(Z, Y[int])
        self.assertNotEqual(Z, Y[T])

        self.assertTrue(str(Z).endswith(
            '.C[typing.Tuple[str, int]]')) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:25,代码来源:test_typing.py

示例9: test_pickle

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def test_pickle(self):
        global C  # pickle wants to reference the class by name
        T = TypeVar('T')

        class B(Generic[T]):
            pass

        class C(B[int]):
            pass

        c = C()
        c.foo = 42
        c.bar = 'abc'
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            z = pickle.dumps(c, proto)
            x = pickle.loads(z)
            self.assertEqual(x.foo, 42)
            self.assertEqual(x.bar, 'abc')
            self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
        simples = [Any, Union, Tuple, Callable, ClassVar, List, typing.Iterable]
        for s in simples:
            for proto in range(pickle.HIGHEST_PROTOCOL + 1):
                z = pickle.dumps(s, proto)
                x = pickle.loads(z)
                self.assertEqual(s, x) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:27,代码来源:test_typing.py

示例10: test_parameterized_slots

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def test_parameterized_slots(self):
        T = TypeVar('T')
        class C(Generic[T]):
            __slots__ = ('potato',)

        c = C()
        c_int = C[int]()
        self.assertEqual(C.__slots__, C[str].__slots__)

        c.potato = 0
        c_int.potato = 0
        with self.assertRaises(AttributeError):
            c.tomato = 0
        with self.assertRaises(AttributeError):
            c_int.tomato = 0

        def foo(x: C['C']): ...
        self.assertEqual(get_type_hints(foo, globals(), locals())['x'], C[C])
        self.assertEqual(get_type_hints(foo, globals(), locals())['x'].__slots__,
                         C.__slots__)
        self.assertEqual(copy(C[int]), deepcopy(C[int])) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:23,代码来源:test_typing.py

示例11: test_type_erasure

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def test_type_erasure(self):
        T = TypeVar('T')

        class Node(Generic[T]):
            def __init__(self, label: T,
                         left: 'Node[T]' = None,
                         right: 'Node[T]' = None):
                self.label = label  # type: T
                self.left = left  # type: Optional[Node[T]]
                self.right = right  # type: Optional[Node[T]]

        def foo(x: T):
            a = Node(x)
            b = Node[T](x)
            c = Node[Any](x)
            self.assertIs(type(a), Node)
            self.assertIs(type(b), Node)
            self.assertIs(type(c), Node)
            self.assertEqual(a.label, x)
            self.assertEqual(b.label, x)
            self.assertEqual(c.label, x)

        foo(42) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:25,代码来源:test_typing.py

示例12: _setup_player_and_team_types

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def _setup_player_and_team_types(self) -> None:
        """Pull player and team types from our typing.Generic params."""

        # TODO: There are proper calls for pulling these in Python 3.8;
        # should update this code when we adopt that.
        # NOTE: If we get Any as PlayerType or TeamType (generally due
        # to no generic params being passed) we automatically use the
        # base class types, but also warn the user since this will mean
        # less type safety for that class. (its better to pass the base
        # player/team types explicitly vs. having them be Any)
        if not TYPE_CHECKING:
            self._playertype = type(self).__orig_bases__[-1].__args__[0]
            if not isinstance(self._playertype, type):
                self._playertype = Player
                print(f'ERROR: {type(self)} was not passed a Player'
                      f' type argument; please explicitly pass ba.Player'
                      f' if you do not want to override it.')
            self._teamtype = type(self).__orig_bases__[-1].__args__[1]
            if not isinstance(self._teamtype, type):
                self._teamtype = Team
                print(f'ERROR: {type(self)} was not passed a Team'
                      f' type argument; please explicitly pass ba.Team'
                      f' if you do not want to override it.')
        assert issubclass(self._playertype, Player)
        assert issubclass(self._teamtype, Team) 
开发者ID:efroemling,项目名称:ballistica,代码行数:27,代码来源:_activity.py

示例13: test_MyGeneric_OK_and_not_OK

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [as 别名]
def test_MyGeneric_OK_and_not_OK():
    for element1 in diverse_collection:
        for element2 in diverse_collection:
            if type(element1) == type(element2):
                continue
            mygen = MyGeneric(element1)
            mygen.append(element1)  # binds X
            mygen.append(element1)  # checks X binding: OK
            print(element1, element2)
            if (issubclass(type(element1), type(element2)) or
                    issubclass(type(element2), type(element1))):
                mygen.append(element2)  # conforms to X binding
            else:
                with expected(tc.InputParameterError("")):
                    mygen.append(element2)  # violates X binding

# TODO: test Generic class with multiple inheritance

############################################################################
# type variable with bound or constraint 
开发者ID:prechelt,项目名称:typecheck-decorator,代码行数:22,代码来源:test_typing_annotations.py

示例14: _get_protocol_attrs

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [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 
开发者ID:thombashi,项目名称:pytablewriter,代码行数:19,代码来源:_typing.py

示例15: __class_getitem__

# 需要导入模块: import typing [as 别名]
# 或者: from typing import Generic [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) 
开发者ID:thombashi,项目名称:pytablewriter,代码行数:26,代码来源:_typing.py


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