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


Python typing.get_type_hints函数代码示例

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


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

示例1: test_generics_replacement

    def test_generics_replacement(self):
        """
        Most basic change. Confirm that generic parameters are actually swapped
        out on child classes.
        """
        Domain = hktyping.HKTypeVar('Domain')
        Codomain = hktyping.HKTypeVar('Codomain')

        class Functor(hktyping.HKGeneric[Domain, Codomain]):
            def fmap_like(self, function: Domain) -> Codomain:
                pass
        class ListFunctor(Functor[AnyCategory, ListCategory]):
            pass
        listf = ListFunctor()

        self.assertEqual(Functor.__parameters__, (Domain, Codomain))
        self.assertEqual(ListFunctor.__parameters__, (AnyCategory, ListCategory))
        self.assertEqual(listf.__parameters__, (AnyCategory, ListCategory))

        #
        #  THIS IS BAD - AND I SHOULD FEEL BAD
        #   It looks like the replacement is occuring to the parent, which is terrible
        #
        self.assertNotEqual(
            typing.get_type_hints(Functor.fmap_like),
            {'function': Domain, 'return': Codomain})
        # These are correct
        self.assertEqual(
            typing.get_type_hints(ListFunctor.fmap_like),
            {'function': AnyCategory, 'return': ListCategory})
        self.assertEqual(
            typing.get_type_hints(listf.fmap_like),
            {'function': AnyCategory, 'return': ListCategory})
开发者ID:OaklandPeters,项目名称:learning_monads,代码行数:33,代码来源:test.py

示例2: test_delayed_syntax_error

    def test_delayed_syntax_error(self):

        def foo(a: 'Node[T'):
            pass

        with self.assertRaises(SyntaxError):
            get_type_hints(foo)
开发者ID:Alkalit,项目名称:cpython,代码行数:7,代码来源:test_typing.py

示例3: test_basics

    def test_basics(self):

        class Node(Generic[T]):

            def __init__(self, label: T):
                self.label = label
                self.left = self.right = None

            def add_both(self,
                         left: 'Optional[Node[T]]',
                         right: 'Node[T]' = None,
                         stuff: int = None,
                         blah=None):
                self.left = left
                self.right = right

            def add_left(self, node: Optional['Node[T]']):
                self.add_both(node, None)

            def add_right(self, node: 'Node[T]' = None):
                self.add_both(None, node)

        t = Node[int]
        both_hints = get_type_hints(t.add_both, globals(), locals())
        self.assertEqual(both_hints['left'], Optional[Node[T]])
        self.assertEqual(both_hints['right'], Optional[Node[T]])
        self.assertEqual(both_hints['left'], both_hints['right'])
        self.assertEqual(both_hints['stuff'], Optional[int])
        self.assertNotIn('blah', both_hints)

        left_hints = get_type_hints(t.add_left, globals(), locals())
        self.assertEqual(left_hints['node'], Optional[Node[T]])

        right_hints = get_type_hints(t.add_right, globals(), locals())
        self.assertEqual(right_hints['node'], Optional[Node[T]])
开发者ID:ChaiYuanUMN,项目名称:mypy,代码行数:35,代码来源:test_typing.py

示例4: test_type_error

    def test_type_error(self):

        def foo(a: Tuple['42']):
            pass

        with self.assertRaises(TypeError):
            get_type_hints(foo)
开发者ID:Alkalit,项目名称:cpython,代码行数:7,代码来源:test_typing.py

示例5: test_name_error

    def test_name_error(self):

        def foo(a: 'Noode[T]'):
            pass

        with self.assertRaises(NameError):
            get_type_hints(foo, locals())
开发者ID:Alkalit,项目名称:cpython,代码行数:7,代码来源:test_typing.py

示例6: test_basics

    def test_basics(self):

        class Node(Generic[T]):

            def __init__(self, label: T):
                self.label = label
                self.left = self.right = None

            def add_both(self,
                         left: 'Optional[Node[T]]',
                         right: 'Node[T]' = None,
                         stuff: int = None,
                         blah=None):
                self.left = left
                self.right = right

            def add_left(self, node: Optional['Node[T]']):
                self.add_both(node, None)

            def add_right(self, node: 'Node[T]' = None):
                self.add_both(None, node)

        t = Node[int]
        both_hints = get_type_hints(t.add_both, globals(), locals())
        assert both_hints['left'] == both_hints['right'] == Optional[Node[T]]
        assert both_hints['stuff'] == Optional[int]
        assert 'blah' not in both_hints

        left_hints = get_type_hints(t.add_left, globals(), locals())
        assert left_hints['node'] == Optional[Node[T]]

        right_hints = get_type_hints(t.add_right, globals(), locals())
        assert right_hints['node'] == Optional[Node[T]]
开发者ID:Alkalit,项目名称:cpython,代码行数:33,代码来源:test_typing.py

示例7: test_basics

    def test_basics(self):
        class Node(Generic[T]):
            def __init__(self, label: T):
                self.label = label
                self.left = self.right = None

            def add_both(self, left: "Optional[Node[T]]", right: "Node[T]" = None, stuff: int = None, blah=None):
                self.left = left
                self.right = right

            def add_left(self, node: Optional["Node[T]"]):
                self.add_both(node, None)

            def add_right(self, node: "Node[T]" = None):
                self.add_both(None, node)

        t = Node[int]
        both_hints = get_type_hints(t.add_both, globals(), locals())
        assert both_hints["left"] == both_hints["right"] == Optional[Node[T]]
        assert both_hints["stuff"] == Optional[int]
        assert "blah" not in both_hints

        left_hints = get_type_hints(t.add_left, globals(), locals())
        assert left_hints["node"] == Optional[Node[T]]

        right_hints = get_type_hints(t.add_right, globals(), locals())
        assert right_hints["node"] == Optional[Node[T]]
开发者ID:Martinpku,项目名称:typing,代码行数:27,代码来源:test_typing.py

示例8: test_basics

    def test_basics(self):
        class Node(Generic[T]):
            def __init__(self, label: T):
                self.label = label
                self.left = self.right = None

            def add_both(self, left: "Optional[Node[T]]", right: "Node[T]" = None, stuff: int = None, blah=None):
                self.left = left
                self.right = right

            def add_left(self, node: Optional["Node[T]"]):
                self.add_both(node, None)

            def add_right(self, node: "Node[T]" = None):
                self.add_both(None, node)

        t = Node[int]
        both_hints = get_type_hints(t.add_both, globals(), locals())
        self.assertEqual(both_hints["left"], Optional[Node[T]])
        self.assertEqual(both_hints["right"], Optional[Node[T]])
        self.assertEqual(both_hints["left"], both_hints["right"])
        self.assertEqual(both_hints["stuff"], Optional[int])
        self.assertNotIn("blah", both_hints)

        left_hints = get_type_hints(t.add_left, globals(), locals())
        self.assertEqual(left_hints["node"], Optional[Node[T]])

        right_hints = get_type_hints(t.add_right, globals(), locals())
        self.assertEqual(right_hints["node"], Optional[Node[T]])
开发者ID:GSmurf,项目名称:typing,代码行数:29,代码来源:test_typing.py

示例9: test_standard_generics

    def test_standard_generics(self):
        Domain = typing.TypeVar('Domain')
        Codomain = typing.TypeVar('Codomain')

        class Functor(typing.Generic[Domain, Codomain]):
            def fmap_like(self, function: Domain) -> Codomain:
                pass
        class ListFunctor(Functor[AnyCategory, ListCategory]):
            pass
        listf = ListFunctor()

        self.assertEqual(Functor.__parameters__, (Domain, Codomain))
        self.assertEqual(ListFunctor.__parameters__, (AnyCategory, ListCategory))
        self.assertEqual(listf.__parameters__, (AnyCategory, ListCategory))


        self.assertEqual(
            typing.get_type_hints(Functor.fmap_like),
            {'function': Domain, 'return': Codomain})
        # This is bad behavior - the __annotations__ on methods on our child class & instances
        #   does not reflect the changes to __parameters__
        #   However, this is the default behavior of typing, so I'm testing for it
        self.assertEqual(
            typing.get_type_hints(ListFunctor.fmap_like),
            {'function': Domain, 'return': Codomain})
        self.assertEqual(
            typing.get_type_hints(listf.fmap_like),
            {'function': Domain, 'return': Codomain})
开发者ID:OaklandPeters,项目名称:learning_monads,代码行数:28,代码来源:test.py

示例10: test_no_type_check_class

    def test_no_type_check_class(self):
        @no_type_check
        class C:
            def foo(a: "whatevers") -> {}:
                pass

        cth = get_type_hints(C.foo)
        self.assertEqual(cth, {})
        ith = get_type_hints(C().foo)
        self.assertEqual(ith, {})
开发者ID:GSmurf,项目名称:typing,代码行数:10,代码来源:test_typing.py

示例11: test_union_forward

    def test_union_forward(self):

        def foo(a: Union['T']):
            pass

        self.assertEqual(get_type_hints(foo, globals(), locals()),
                         {'a': Union[T]})
开发者ID:Alkalit,项目名称:cpython,代码行数:7,代码来源:test_typing.py

示例12: _annotations_corrector

def _annotations_corrector(function, bases, parameters):
    """
    """
    annotations = typing.get_type_hints(function)    
    accumulator = dict()
    for key, value in annotations.items():
        # If it is an unfilled typevar
        if isinstance(value, typing.TypeVar):
            # Find parent with generic version of this parameter
            position = None
            for parent in bases:
                if value in getattr(parent, '__parameters__', []):
                    position = parent.__parameters__.index(value)
            if position is None:
                raise ValueError("Could not find position in __parameters__ of parent classes")

            # If this is a structured reference, resolve it
            if _is_structured_forward_ref(value):
                base = parameters[position]
                tinyns = {value._structured_forward_ref_name: parameters[position]}
                # my_lambda = "lambda {0}: {1}".format(value._structured_forward_ref_name, value._structured_forward_ref_code)
                concrete = eval(value._structured_forward_ref_code, tinyns)                
            else:
                concrete = parameters[position]

            accumulator[key] = concrete
        else:
            accumulator[key] = value
    return accumulator
开发者ID:OaklandPeters,项目名称:learning_monads,代码行数:29,代码来源:higher_kinded.py

示例13: fields

    def fields(self) -> Dict[str, _Field]:
        def make_factory(value: object) -> Callable[[], Any]:
            return lambda: value

        if self._fields is None:
            hints = typing.get_type_hints(self.type)
            # This is gnarly. Sorry. For each field, store its default_factory if present; otherwise
            # create a factory returning its default if present; otherwise None. Default parameter
            # in the lambda is a ~~hack~~ to avoid messing up the variable binding.
            fields: Dict[str, _Field] = {
                field.name: _Field(
                    field.default_factory  # type: ignore
                    if field.default_factory is not MISSING  # type: ignore
                    else (
                        (make_factory(field.default))
                        if field.default is not MISSING
                        else None
                    ),
                    hints[field.name],
                )
                for field in dataclasses.fields(self.type)
            }

            self._fields = fields

        return self._fields
开发者ID:i80and,项目名称:flutter,代码行数:26,代码来源:__init__.py

示例14: generate_new_enforcer

def generate_new_enforcer(func, generic, parent_root, instance_of, settings):
    """
    Private function for generating new Enforcer instances for the incoming function
    """
    if parent_root is not None:
        if type(parent_root) is not Validator:
            raise TypeError('Parent validator must be a Validator')

    if instance_of is not None:
        if type(instance_of) is not GenericProxy:
            raise TypeError('Instance of a generic must be derived from a valid Generic Proxy')

    if generic:
        hints = OrderedDict()

        if instance_of:
            func = instance_of

        func_type = type(func)

        has_origin = func.__origin__ is not None

        # Collects generic's parameters - TypeVar-s specified on itself or on origin (if constrained)
        if not func.__parameters__ and (not has_origin or not func.__origin__.__parameters__):
            raise TypeError('User defined generic is invalid')

        parameters = func.__parameters__ if func.__parameters__ else func.__origin__.__parameters__

        # Maps parameter names to parameters, while preserving the order of their definition
        for param in parameters:
            hints[param.__name__] = EnhancedTypeVar(param.__name__, type_var=param)

        # Verifies that constraints do not contradict generic's parameter definition
        # and bounds parameters to constraints (if constrained)
        bound = bool(func.__args__)
        if bound:
            for i, param in enumerate(hints.values()):
                arg = func.__args__[i]
                if is_type_of_type(arg, param):
                    param.__bound__ = arg
                else:
                    raise TypeError('User defined generic does not accept provided constraints')

        # NOTE:
        # Signature in generics should always point to the original unconstrained generic
        # This applies even to the instances of such Generics

        if has_origin:
            signature = func.__origin__
        else:
            signature = func.__wrapped__ if func_type is GenericProxy else func

        validator = init_validator(hints, parent_root)
    else:
        bound = False
        signature = inspect.signature(func)
        hints = typing.get_type_hints(func)
        validator = init_validator(hints, parent_root)

    return Enforcer(validator, signature, hints, generic, bound, settings)
开发者ID:RussBaz,项目名称:enforce,代码行数:60,代码来源:enforcers.py

示例15: test_callable_with_ellipsis_forward

    def test_callable_with_ellipsis_forward(self):

        def foo(a: 'Callable[..., T]'):
            pass

        self.assertEqual(get_type_hints(foo, globals(), locals()),
                         {'a': Callable[..., T]})
开发者ID:brettcannon,项目名称:typing,代码行数:7,代码来源:test_typing.py


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