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


Python typing.get_type_hints方法代码示例

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


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

示例1: resolve_types

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def resolve_types(cls, global_ns=None, local_ns=None):
    """
    Resolve any strings and forward annotations in type annotations.

    :param type cls: Class to resolve.
    :param globalns: Dictionary containing global variables, if needed.
    :param localns: Dictionary containing local variables, if needed.
    :raise TypeError: If *cls* is not a class.
    :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
           class.
    :raise NameError: If types cannot be resolved because of missing variables.

    """
    hints = typing.get_type_hints(cls, globalns=global_ns, localns=local_ns)
    for field in attr.fields(cls):
        if field.name in hints:
            # Since fields have been frozen we must work around it.
            object.__setattr__(field, "type", hints[field.name]) 
开发者ID:bloomberg,项目名称:attrs-strict,代码行数:20,代码来源:_type_validation.py

示例2: _get_type_from_hint

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def _get_type_from_hint(hint):
    if _is_list_like(hint):
        [type_] = _ti_get_args(hint)
        return List[type_]
    elif _ti_get_origin(hint) is Union:
        # Flatten Union[type, NoneType] (== Optional[type]) to type.
        # get_type_hints also appends NoneType to unions for parameters
        # defaulting to None.
        args = [arg for arg in _ti_get_args(hint) if arg is not type(None)]
        if len(args) > 1:
            if any(_is_list_like(subtype) for subtype in args):
                raise ValueError(
                    'unsupported union including container type: {}'
                    .format(hint))
            return Union[tuple(args)]
        else:
            return args[0]
    return hint 
开发者ID:anntzer,项目名称:defopt,代码行数:20,代码来源:defopt.py

示例3: test_parameterized_slots

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

示例4: test_meta_no_type_check

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def test_meta_no_type_check(self):

        @no_type_check_decorator
        def magic_decorator(deco):
            return deco

        self.assertEqual(magic_decorator.__name__, 'magic_decorator')

        @magic_decorator
        def foo(a: 'whatevers') -> {}:
            pass

        @magic_decorator
        class C:
            def foo(a: 'whatevers') -> {}:
                pass

        self.assertEqual(foo.__name__, 'foo')
        th = get_type_hints(foo)
        self.assertEqual(th, {})
        cth = get_type_hints(C.foo)
        self.assertEqual(cth, {})
        ith = get_type_hints(C().foo)
        self.assertEqual(ith, {}) 
开发者ID:ShikyoKira,项目名称:Project-New-Reign---Nemesis-Main,代码行数:26,代码来源:test_typing.py

示例5: _has_type_hints

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def _has_type_hints(func0, func_class = None, nesting = None):
    actual_func = util._actualfunc(func0)
    func = as_stub_func_if_any(actual_func, func0, func_class, nesting)
    stub_func = func
    func = util._actualfunc(func)
    tpHints = _tpHints_from_annotations(func0, actual_func, stub_func, func)
    if not tpHints is None:
        return True
    try:
        tpHints = typing.get_type_hints(func)
    except NameError:
        # Some typehint caused this NameError, so typhints are present in some form
        return True
    except TypeError:
        # func seems to be not suitable to have type hints
        return False
    except AttributeError:
        # func seems to be not suitable to have type hints
        return False
    try:
        tpStr = _get_typestrings(func, False)
        return not ((tpStr is None or tpStr[0] is None) and (tpHints is None or not tpHints))
    except TypeError:
        return False 
开发者ID:Stewori,项目名称:pytypes,代码行数:26,代码来源:type_util.py

示例6: _get_type_hints

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def _get_type_hints(func, args = None, res = None, infer_defaults = None):
    """Helper for get_type_hints.
    """
    if args is None or res is None:
        args2, res2 = _get_types(func, util.is_classmethod(func),
                util.is_method(func), unspecified_type = type(NotImplemented),
                infer_defaults = infer_defaults)
        if args is None:
            args = args2
        if res is None:
            res = res2
    slf = 1 if util.is_method(func) else 0
    argNames = util.getargnames(util.getargspecs(util._actualfunc(func)))
    result = {}
    if not args is Any:
        prms = get_Tuple_params(args)
        for i in range(slf, len(argNames)):
            if not prms[i-slf] is type(NotImplemented):
                result[argNames[i]] = prms[i-slf]
    result['return'] = res
    return result 
开发者ID:Stewori,项目名称:pytypes,代码行数:23,代码来源:type_util.py

示例7: read

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def read(self, reader: StructReader):
        result = copy.copy(self)

        # Use the typehints to guide reading
        hints = get_type_hints(self.__class__)
        for name, readable in hints.items():
            # As typehints are at the class level, we need to copy them if its a readable
            if isinstance(readable, Readable):
                readable = copy.copy(readable)

            try:
                value = reader.read_struct(readable)
                setattr(result, name, value)
            except Exception as ex:
                classname = type(self).__name__
                raise Exception(f"Failed to read prop {name} in {classname}") from ex

        return result 
开发者ID:gatheringhallstudios,项目名称:MHWorldData,代码行数:20,代码来源:structreader.py

示例8: _coro_executor

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def _coro_executor(self, coro_ref: Callable[..., Coroutine]):
        params: Dict[str, Any] = {}
        unresolved_params = []
        coro_arguments = inspect.signature(coro_ref).parameters
        type_annotations = typing.get_type_hints(coro_ref)
        type_annotations.pop("return", None)

        if coro_arguments:
            if not type_annotations:
                raise MissingTypeAnnotationError(
                    f"{coro_ref} has no type annotation"
                )

            for param_name, param_type in type_annotations.items():
                param_value = self.resolve_param(param_type, param_name)
                if param_value is not None:
                    params[param_name] = param_value
                else:
                    unresolved_params.append((param_name, param_type))
            if unresolved_params:
                raise TypeError(
                    f"Unresolved params for coroutine {coro_ref}: {unresolved_params}"
                )
        return await coro_ref(**params) 
开发者ID:b2wdigital,项目名称:async-worker,代码行数:26,代码来源:resolver.py

示例9: _check_function_contracts

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def _check_function_contracts(wrapped, instance, args, kwargs):
    params = wrapped.__code__.co_varnames[:wrapped.__code__.co_argcount]
    annotations = typing.get_type_hints(wrapped)
    args_with_self = (instance,) + args if instance else args

    # Check function parameter types
    for arg, param in zip(args_with_self, params):
        if param in annotations:
            try:
                check_type(param, arg, annotations[param])
            except TypeError:
                raise AssertionError(
                    f'{wrapped.__name__} argument {repr(arg)} did not match type annotation for parameter \
                        "{param}: {annotations[param]}"')

    # Check function preconditions
    preconditions = parse_assertions(wrapped.__doc__ or '')
    function_locals = dict(zip(params, args_with_self))
    _check_assertions(wrapped, function_locals, preconditions)

    # Check return type
    r = wrapped(*args, **kwargs)
    if 'return' in annotations:
        return_type = annotations['return']
        try:
            check_type('return', r, return_type)
        except TypeError:
            raise AssertionError(
                f'{wrapped.__name__} return value {r} does not match annotated return type {return_type}')

    return r 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:33,代码来源:__init__.py

示例10: _check_class_type_annotations

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def _check_class_type_annotations(instance: Any) -> None:
    """Check that the type annotations for the class still hold.
    """
    klass = instance.__class__
    cls_annotations = typing.get_type_hints(klass)

    for attr, annotation in cls_annotations.items():
        value = getattr(instance, attr)
        try:
            check_type(attr, value, annotation)
        except TypeError:
            raise AssertionError(
                f'{repr(value)} did not match type annotation for attribute "{attr}: {annotation}"') 
开发者ID:pyta-uoft,项目名称:pyta,代码行数:15,代码来源:__init__.py

示例11: generate_id2type_from_forward

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def generate_id2type_from_forward(model, args, is_debug=False):
    code = utils.clip_head(inspect.getsource(model.forward))
    tree = gast.ast_to_gast(ast.parse(code))
    module = sys.modules[model.forward.__module__]
    node2type, subroutine_node = generate_node2type(
            tree, (model,) + args, is_debug=is_debug, module=module,
            type_hints=typing.get_type_hints(model.forward))
    node2id = generate_node2id(tree, subroutine_node)
    id2type = generate_id2type(node2type, node2id)
    return id2type


# For debug 
开发者ID:pfnet-research,项目名称:chainer-compiler,代码行数:15,代码来源:type_inference_tools.py

示例12: generate_type_inference_results

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def generate_type_inference_results(model, forward_args, is_debug=False):
    code = utils.clip_head(inspect.getsource(model.forward))
    node = gast.ast_to_gast(ast.parse(code))
    # node = Canonicalizer().visit(node)
    module = sys.modules[model.forward.__module__]
    node2type, subroutine_node = generate_node2type(
        node, (model,) + forward_args, is_debug=is_debug, module=module,
        type_hints=typing.get_type_hints(model.forward))
    node2id = generate_node2id(node, subroutine_node)
    id2type = generate_id2type(node2type, node2id)
    id2node = generate_id2node(node2id)
    return id2type, id2node 
开发者ID:pfnet-research,项目名称:chainer-compiler,代码行数:14,代码来源:type_inference_tools.py

示例13: infer_user_defined_function

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def infer_user_defined_function(self, func, ty_args, node):
        if isinstance(func, (types.FunctionType, types.MethodType)):
            func_body = func

            if isinstance(node.func, gast.Attribute):
                ty_self = self.nodetype[node.func.value]
                ty_args = [ty_self] + ty_args

        else:
            # defined with __call__
            if isinstance(func, chainer.Chain) or isinstance(func, nn.Module):
                func_body = func.forward
            else:
                func_body = func.__call__

            ty_self = type_of_value(func)
            ty_args = [ty_self] + ty_args

        code = clip_head(inspect.getsource(func_body))
        # FunctionDef of called subroutine
        func_node = gast.ast_to_gast(ast.parse(code)).body[0]
        if node not in self.subroutine_node.keys():
            self.subroutine_node[node] = [func_node]
        else:
            self.subroutine_node[node].append(func_node)
        tc = InferenceEngine(is_debug=self.is_debug,
                module=sys.modules[func.__module__])
        tc.infer_function(func_node, ty_args,
                type_hints=typing.get_type_hints(func_body))

        # copy nodetype and subroutine_node from subroutine
        utils.add_dict(self.nodetype, tc.nodetype)
        utils.add_dict(self.subroutine_node, tc.subroutine_node)
        return tc.nodetype[func_node].retty


    # ================================ mod ===================================== 
开发者ID:pfnet-research,项目名称:chainer-compiler,代码行数:39,代码来源:type_inference.py

示例14: _get_annotations

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def _get_annotations(self) -> Dict[str, Any]:
        """Returns a dictionary mapping variable names to their type annotations."""
        return self._get_from_self_and_super(
            extract_func=lambda super_class: dict(get_type_hints(super_class))
        ) 
开发者ID:swansonk14,项目名称:typed-argument-parser,代码行数:7,代码来源:tap.py

示例15: definition

# 需要导入模块: import typing [as 别名]
# 或者: from typing import get_type_hints [as 别名]
def definition(self):
        return {
            "type": "object",
            "properties": {
                key: serialize_schema(schema)
                for key, schema in chain(
                    {key: getattr(self.cls, key) for key in dir(self.cls)}.items(),
                    typing.get_type_hints(self.cls).items(),
                )
                if not key.startswith("_")
            },
            **super().serialize(),
        } 
开发者ID:huge-success,项目名称:sanic-openapi,代码行数:15,代码来源:doc.py


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