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