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


Python typing_inspect.get_args方法代码示例

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


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

示例1: get_literals

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_args [as 别名]
def get_literals(literal: Literal, variable: str) -> Tuple[Callable[[str], Any], List[str]]:
    """Extracts the values from a Literal type and ensures that the values are all primitive types."""
    literals = list(get_args(literal))

    if not all(isinstance(literal, PRIMITIVES) for literal in literals):
        raise ValueError(
            f'The type for variable "{variable}" contains a literal'
            f'of a non-primitive type e.g. (str, int, float, bool).\n'
            f'Currently only primitive-typed literals are supported.'
        )

    str_to_literal = {str(literal): literal for literal in literals}

    if len(literals) != len(str_to_literal):
        raise ValueError('All literals must have unique string representations')

    def var_type(arg: str) -> Any:
        return str_to_literal[arg]

    return var_type, literals 
开发者ID:swansonk14,项目名称:typed-argument-parser,代码行数:22,代码来源:utils.py

示例2: _check_tuple_type

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_args [as 别名]
def _check_tuple_type(type_, value, raise_error, instance_type):
    if not isinstance(value, instance_type):
        raise_error(str(type_), value)

    eltype = None
    ellipsis = False
    type_args = typing_inspect.get_args(type_, evaluate=True)

    for i, el in enumerate(value):
        if not ellipsis:
            new_eltype = type_args[i]
            if new_eltype is Ellipsis:
                ellipsis = True
            else:
                eltype = new_eltype
        if eltype is not None:
            _check_type(eltype, el, raise_error) 
开发者ID:edgedb,项目名称:edgedb,代码行数:19,代码来源:base.py

示例3: _is_optional

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_args [as 别名]
def _is_optional(type_):
    return (typing_inspect.is_union_type(type_) and
            type(None) in typing_inspect.get_args(type_, evaluate=True)) 
开发者ID:edgedb,项目名称:edgedb,代码行数:5,代码来源:base.py

示例4: _check_container_type

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_args [as 别名]
def _check_container_type(type_, value, raise_error, instance_type):
    if not isinstance(value, instance_type):
        raise_error(str(type_), value)

    type_args = typing_inspect.get_args(type_, evaluate=True)
    eltype = type_args[0]
    for el in value:
        _check_type(eltype, el, raise_error) 
开发者ID:edgedb,项目名称:edgedb,代码行数:10,代码来源:base.py

示例5: _check_mapping_type

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_args [as 别名]
def _check_mapping_type(type_, value, raise_error, instance_type):
    if not isinstance(value, instance_type):
        raise_error(str(type_), value)

    type_args = typing_inspect.get_args(type_, evaluate=True)
    ktype = type_args[0]
    vtype = type_args[1]
    for k, v in value.items():
        _check_type(ktype, k, raise_error)
        if not k and not _is_optional(ktype):
            raise RuntimeError('empty key in map')
        _check_type(vtype, v, raise_error) 
开发者ID:edgedb,项目名称:edgedb,代码行数:14,代码来源:base.py

示例6: get_args

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_args [as 别名]
def get_args(cls) -> Tuple:
        if typing_inspect.is_union_type(cls):
            try:
                return cls.__union_params__
            except AttributeError:
                pass
            return cls.__args__
        elif issubclass(cls, List):
            return cls.__args__
        else:
            raise ValueError("Cannot get type arguments for {}".format(cls)) 
开发者ID:stanfordnqp,项目名称:spins-b,代码行数:13,代码来源:schema.py

示例7: _ti_get_args

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_args [as 别名]
def _ti_get_args(tp):
        import typing_inspect as ti
        if type(tp) is type(Literal):  # Py<=3.6.
            return tp.__values__
        return ti.get_args(tp, evaluate=True)  # evaluate=True default on Py>=3.7. 
开发者ID:anntzer,项目名称:defopt,代码行数:7,代码来源:defopt.py

示例8: _check_annotation

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_args [as 别名]
def _check_annotation(f_type, f_fullname, f_default):
    if typing_inspect.is_tuple_type(f_type):
        if f_default is not None:
            raise RuntimeError(
                f'invalid type annotation on {f_fullname}: '
                f'default is defined for tuple type')

        f_default = tuple

    elif typing_inspect.is_union_type(f_type):
        for t in typing_inspect.get_args(f_type, evaluate=True):
            _check_annotation(t, f_fullname, f_default)

    elif typing_inspect.is_generic_type(f_type):
        if f_default is not None:
            raise RuntimeError(
                f'invalid type annotation on {f_fullname}: '
                f'default is defined for container type '
                f'{f_type!r}')

        ot = typing_inspect.get_origin(f_type)
        if ot is None:
            raise RuntimeError(
                f'cannot find origin of a generic type {f_type}')

        if ot in (list, List, collections.abc.Sequence):
            f_default = list
        elif ot in (set, Set):
            f_default = set
        elif ot in (frozenset, FrozenSet):
            f_default = frozenset
        elif ot in (dict, Dict):
            f_default = dict
        else:
            raise RuntimeError(
                f'invalid type annotation on {f_fullname}: '
                f'{f_type!r} is not supported')

    elif f_type is not None:
        if f_type is Any:
            f_type = object

        if not isinstance(f_type, type):
            raise RuntimeError(
                f'invalid type annotation on {f_fullname}: '
                f'{f_type!r} is not a type')

        if typeutils.is_container_type(f_type):
            if f_default is not None:
                raise RuntimeError(
                    f'invalid type annotation on {f_fullname}: '
                    f'default is defined for container type '
                    f'{f_type!r}')
            f_default = f_type

    return f_default 
开发者ID:edgedb,项目名称:edgedb,代码行数:58,代码来源:base.py

示例9: _init_parametric_base

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_args [as 别名]
def _init_parametric_base(cls) -> None:
        """Initialize a direct subclass of ParametricType"""

        # Direct subclasses of ParametricType must declare
        # ClassVar attributes corresponding to the Generic type vars.
        # For example:
        #     class P(ParametricType, Generic[T, V]):
        #         t: ClassVar[Type[T]]
        #         v: ClassVar[Type[V]]

        params = getattr(cls, '__parameters__', None)

        if not params:
            raise TypeError(
                f'{cls} must be declared as Generic'
            )

        mod = sys.modules[cls.__module__]
        annos = get_type_hints(cls, mod.__dict__)
        param_map = {}

        for attr, t in annos.items():
            if not typing_inspect.is_classvar(t):
                continue

            args = typing_inspect.get_args(t)
            # ClassVar constructor should have the check, but be extra safe.
            assert len(args) == 1

            arg = args[0]
            if typing_inspect.get_origin(arg) != type:
                continue

            arg_args = typing_inspect.get_args(arg)
            # Likewise, rely on Type checking its stuff in the constructor
            assert len(arg_args) == 1

            if not typing_inspect.is_typevar(arg_args[0]):
                continue

            if arg_args[0] in params:
                param_map[arg_args[0]] = attr

        for param in params:
            if param not in param_map:
                raise TypeError(
                    f'{cls.__name__}: missing ClassVar for'
                    f' generic parameter {param}'
                )

        cls._type_param_map = param_map 
开发者ID:edgedb,项目名称:edgedb,代码行数:53,代码来源:parametric.py

示例10: _init_parametric_user

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_args [as 别名]
def _init_parametric_user(cls) -> None:
        """Initialize an indirect descendant of ParametricType."""

        # For ParametricType grandchildren we have to deal with possible
        # TypeVar remapping and generally check for type sanity.

        ob = getattr(cls, '__orig_bases__', ())
        for b in ob:
            if (
                isinstance(b, type)
                and issubclass(b, ParametricType)
                and b is not ParametricType
            ):
                raise TypeError(
                    f'{cls.__name__}: missing one or more type arguments for'
                    f' base {b.__name__!r}'
                )

            if not typing_inspect.is_generic_type(b):
                continue

            org = typing_inspect.get_origin(b)
            if not isinstance(org, type):
                continue
            if not issubclass(org, ParametricType):
                continue

            base_params = getattr(org, '__parameters__', ())

            args = typing_inspect.get_args(b)
            expected = len(base_params)
            if len(args) != expected:
                raise TypeError(
                    f'{b.__name__} expects {expected} type arguments'
                    f' got {len(args)}'
                )

            base_map = dict(cls._type_param_map)
            subclass_map = {}

            for i, arg in enumerate(args):
                if not typing_inspect.is_typevar(arg):
                    raise TypeError(
                        f'{b.__name__} expects all arguments to be'
                        f' TypeVars'
                    )

                base_typevar = base_params[i]
                attr = base_map.get(base_typevar)
                if attr is not None:
                    subclass_map[arg] = attr

            if len(subclass_map) != len(base_map):
                raise TypeError(
                    f'{cls.__name__}: missing one or more type arguments for'
                    f' base {org.__name__!r}'
                )

            cls._type_param_map = subclass_map 
开发者ID:edgedb,项目名称:edgedb,代码行数:61,代码来源:parametric.py


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