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


Python typing_inspect.get_origin方法代码示例

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


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

示例1: kind_to_py

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_origin [as 别名]
def kind_to_py(kind):
    if kind is None or kind is typing.Any:
        return 'None', '', False

    name = ""
    if typing_inspect.is_generic_type(kind):
        origin = typing_inspect.get_origin(kind)
        name = origin.__name__
    else:
        name = kind.__name__

    if (kind in basic_types or type(kind) in basic_types):
        return name, type_mapping.get(name) or name, True
    if (name in type_mapping):
        return name, type_mapping[name], True

    suffix = name.lstrip("~")
    return suffix, "(dict, {})".format(suffix), True 
开发者ID:juju,项目名称:python-libjuju,代码行数:20,代码来源:facade.py

示例2: parse_args

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_origin [as 别名]
def parse_args(self: TapType,
                   args: Optional[Sequence[str]] = None,
                   known_only: bool = False) -> TapType:
        """Parses arguments, sets attributes of self equal to the parsed arguments, and processes arguments.

        :param args: List of strings to parse. The default is taken from `sys.argv`.
        :param known_only: If true, ignores extra arguments and only parses known arguments.
        Unparsed arguments are saved to self.extra_args.
        :return: self, which is a Tap instance containing all of the parsed args.
        """
        # Parse args using super class ArgumentParser's parse_args or parse_known_args function
        if known_only:
            default_namespace, self.extra_args = super(Tap, self).parse_known_args(args)
        else:
            default_namespace = super(Tap, self).parse_args(args)

        # Copy parsed arguments to self
        for variable, value in vars(default_namespace).items():
            # Conversion from list to set or tuple
            if variable in self._annotations:
                var_type = get_origin(self._annotations[variable])

                if var_type in (Set, set):
                    value = set(value)
                elif var_type in (Tuple, tuple):
                    value = tuple(value)

            # Set variable in self (and deepcopy)
            setattr(self, variable, deepcopy(value))

        # Process args
        self.process_args()

        # Indicate that args have been parsed
        self._parsed = True

        return self 
开发者ID:swansonk14,项目名称:typed-argument-parser,代码行数:39,代码来源:tap.py

示例3: _check_type_real

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_origin [as 别名]
def _check_type_real(type_, value, raise_error):
    if type_ is None:
        return

    if typing_inspect.is_union_type(type_):
        for t in typing_inspect.get_args(type_, evaluate=True):
            try:
                _check_type(t, value, raise_error)
            except TypeError:
                pass
            else:
                break
        else:
            raise_error(str(type_), value)

    elif typing_inspect.is_tuple_type(type_):
        _check_tuple_type(type_, value, raise_error, tuple)

    elif typing_inspect.is_generic_type(type_):
        ot = typing_inspect.get_origin(type_)

        if ot in (list, List, collections.abc.Sequence):
            _check_container_type(type_, value, raise_error, list)

        elif ot in (set, Set):
            _check_container_type(type_, value, raise_error, set)

        elif ot in (frozenset, FrozenSet):
            _check_container_type(type_, value, raise_error, frozenset)

        elif ot in (dict, Dict):
            _check_mapping_type(type_, value, raise_error, dict)

        elif ot is not None:
            raise TypeError(f'unsupported typing type: {type_!r}')

    elif type_ is not Any:
        if value is not None and not isinstance(value, type_):
            raise_error(type_.__name__, value) 
开发者ID:edgedb,项目名称:edgedb,代码行数:41,代码来源:base.py

示例4: do_explode

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_origin [as 别名]
def do_explode(self, kind):
        if kind in basic_types or type(kind) is typing.TypeVar:
            return False
        if typing_inspect.is_generic_type(kind) and issubclass(typing_inspect.get_origin(kind), Sequence):
            return False
        if typing_inspect.is_generic_type(kind) and issubclass(typing_inspect.get_origin(kind), Mapping):
            return False
        self.clear()
        self.extend(Args(self.schema, kind))
        return True 
开发者ID:juju,项目名称:python-libjuju,代码行数:12,代码来源:facade.py

示例5: ReturnMapping

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_origin [as 别名]
def ReturnMapping(cls):
    # Annotate the method with a return Type
    # so the value can be cast
    def decorator(f):
        @functools.wraps(f)
        async def wrapper(*args, **kwargs):
            nonlocal cls
            reply = await f(*args, **kwargs)
            if cls is None:
                return reply
            if 'error' in reply:
                cls = CLASSES['Error']
            if typing_inspect.is_generic_type(cls) and issubclass(typing_inspect.get_origin(cls), Sequence):
                parameters = typing_inspect.get_parameters(cls)
                result = []
                item_cls = parameters[0]
                for item in reply:
                    result.append(item_cls.from_json(item))
                    """
                    if 'error' in item:
                        cls = CLASSES['Error']
                    else:
                        cls = item_cls
                    result.append(cls.from_json(item))
                    """
            else:
                result = cls.from_json(reply['response'])

            return result
        return wrapper
    return decorator 
开发者ID:juju,项目名称:python-libjuju,代码行数:33,代码来源:facade.py

示例6: _ti_get_origin

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_origin [as 别名]
def _ti_get_origin(tp):
        import typing_inspect as ti
        if type(tp) is type(Literal):  # Py<=3.6.
            return Literal
        origin = ti.get_origin(tp)
        return {  # Py<=3.6.
            typing.List: list,
            typing.Iterable: collections.abc.Iterable,
            typing.Sequence: collections.abc.Sequence,
            typing.Tuple: tuple,
        }.get(origin, origin) 
开发者ID:anntzer,项目名称:defopt,代码行数:13,代码来源:defopt.py

示例7: check_type

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_origin [as 别名]
def check_type(obj, tp):
    if is_union_type(tp):
        return any(check_type(obj, a) for a in tp.__args__)
    else:
        origin = get_origin(tp)
        if origin is None or origin == tp:
            return isinstance(obj, tp)
        else:
            return check_type(obj, origin) 
开发者ID:asyml,项目名称:forte,代码行数:11,代码来源:utils.py

示例8: _check_annotation

# 需要导入模块: import typing_inspect [as 别名]
# 或者: from typing_inspect import get_origin [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_origin [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_origin [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_origin方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。