當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。