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