當前位置: 首頁>>代碼示例>>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_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

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

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

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

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

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

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

示例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;未經允許,請勿轉載。