• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python types.CallableType类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mypy.types.CallableType的典型用法代码示例。如果您正苦于以下问题:Python CallableType类的具体用法?Python CallableType怎么用?Python CallableType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: add_method

def add_method(
        ctx: ClassDefContext,
        name: str,
        args: List[Argument],
        return_type: Type,
        self_type: Optional[Type] = None,
        tvar_def: Optional[TypeVarDef] = None,
) -> None:
    """Adds a new method to a class.
    """
    info = ctx.cls.info
    self_type = self_type or fill_typevars(info)
    function_type = ctx.api.named_type('__builtins__.function')

    args = [Argument(Var('self'), self_type, None, ARG_POS)] + args
    arg_types, arg_names, arg_kinds = [], [], []
    for arg in args:
        assert arg.type_annotation, 'All arguments must be fully typed.'
        arg_types.append(arg.type_annotation)
        arg_names.append(arg.variable.name())
        arg_kinds.append(arg.kind)

    signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type)
    if tvar_def:
        signature.variables = [tvar_def]

    func = FuncDef(name, args, Block([PassStmt()]))
    func.info = info
    func.type = set_callable_name(signature, func)
    func._fullname = info.fullname() + '.' + name
    func.line = info.line

    info.names[name] = SymbolTableNode(MDEF, func, plugin_generated=True)
    info.defn.defs.body.append(func)
开发者ID:chadrik,项目名称:mypy,代码行数:34,代码来源:common.py


示例2: add_method

    def add_method(self,
                   method_name: str, args: List[Argument], ret_type: Type,
                   self_type: Optional[Type] = None,
                   tvd: Optional[TypeVarDef] = None) -> None:
        """Add a method: def <method_name>(self, <args>) -> <ret_type>): ... to info.

        self_type: The type to use for the self argument or None to use the inferred self type.
        tvd: If the method is generic these should be the type variables.
        """
        from mypy.semanal import set_callable_name
        self_type = self_type if self_type is not None else self.self_type
        args = [Argument(Var('self'), self_type, None, ARG_POS)] + args
        arg_types = [arg.type_annotation for arg in args]
        arg_names = [arg.variable.name() for arg in args]
        arg_kinds = [arg.kind for arg in args]
        assert None not in arg_types
        signature = CallableType(cast(List[Type], arg_types), arg_kinds, arg_names,
                                 ret_type, self.function_type)
        if tvd:
            signature.variables = [tvd]
        func = FuncDef(method_name, args, Block([PassStmt()]))
        func.info = self.info
        func.type = set_callable_name(signature, func)
        func._fullname = self.info.fullname() + '.' + method_name
        func.line = self.info.line
        self.info.names[method_name] = SymbolTableNode(MDEF, func)
        # Add the created methods to the body so that they can get further semantic analysis.
        # e.g. Forward Reference Resolution.
        self.info.defn.defs.body.append(func)
开发者ID:sixolet,项目名称:mypy,代码行数:29,代码来源:attrs.py


示例3: is_callable_subtype

def is_callable_subtype(left: CallableType, right: CallableType, ignore_return: bool = False) -> bool:
    """Is left a subtype of right?"""
    # TODO: Support named arguments, **args, etc.
    # Non-type cannot be a subtype of type.
    if right.is_type_obj() and not left.is_type_obj():
        return False
    if right.variables:
        # Subtyping is not currently supported for generic function as the supertype.
        return False
    if left.variables:
        # Apply generic type variables away in left via type inference.
        left = unify_generic_callable(left, right)
        if left is None:
            return False

    # Check return types.
    if not ignore_return and not is_subtype(left.ret_type, right.ret_type):
        return False

    # Check argument types.
    if left.min_args > right.min_args:
        return False
    if left.is_var_arg:
        return is_var_arg_callable_subtype_helper(left, right)
    if right.is_var_arg:
        return False
    if len(left.arg_types) < len(right.arg_types):
        return False
    for i in range(len(right.arg_types)):
        if not is_subtype(right.arg_types[i], left.arg_types[i]):
            return False
    return True
开发者ID:JamesTFarrington,项目名称:mypy,代码行数:32,代码来源:subtypes.py


示例4: add_method

        def add_method(funcname: str,
                       ret: Type,
                       args: List[Argument],
                       name: Optional[str] = None,
                       is_classmethod: bool = False,
                       is_new: bool = False,
                       ) -> None:
            if is_classmethod or is_new:
                first = [Argument(Var('cls'), TypeType.make_normalized(selftype), None, ARG_POS)]
            else:
                first = [Argument(Var('self'), selftype, None, ARG_POS)]
            args = first + args

            types = [arg.type_annotation for arg in args]
            items = [arg.variable.name() for arg in args]
            arg_kinds = [arg.kind for arg in args]
            assert None not in types
            signature = CallableType(cast(List[Type], types), arg_kinds, items, ret,
                                     function_type)
            signature.variables = [tvd]
            func = FuncDef(funcname, args, Block([]))
            func.info = info
            func.is_class = is_classmethod
            func.type = set_callable_name(signature, func)
            func._fullname = info.fullname() + '.' + funcname
            if is_classmethod:
                v = Var(funcname, func.type)
                v.is_classmethod = True
                v.info = info
                v._fullname = func._fullname
                dec = Decorator(func, [NameExpr('classmethod')], v)
                info.names[funcname] = SymbolTableNode(MDEF, dec)
            else:
                info.names[funcname] = SymbolTableNode(MDEF, func)
开发者ID:python,项目名称:mypy,代码行数:34,代码来源:semanal_namedtuple.py


示例5: visit_FunctionDef

    def visit_FunctionDef(self, n: ast35.FunctionDef) -> Node:
        args = self.transform_args(n.args, n.lineno)

        arg_kinds = [arg.kind for arg in args]
        arg_names = [arg.variable.name() for arg in args]
        arg_types = None  # type: List[Type]
        if n.type_comment is not None:
            try:
                func_type_ast = ast35.parse(n.type_comment, '<func_type>', 'func_type')
            except SyntaxError:
                raise TypeCommentParseError(TYPE_COMMENT_SYNTAX_ERROR, n.lineno)
            assert isinstance(func_type_ast, ast35.FunctionType)
            # for ellipsis arg
            if (len(func_type_ast.argtypes) == 1 and
                    isinstance(func_type_ast.argtypes[0], ast35.Ellipsis)):
                arg_types = [a.type_annotation if a.type_annotation is not None else AnyType()
                             for a in args]
            else:
                arg_types = [a if a is not None else AnyType() for
                            a in TypeConverter(line=n.lineno).visit_list(func_type_ast.argtypes)]
            return_type = TypeConverter(line=n.lineno).visit(func_type_ast.returns)

            # add implicit self type
            if self.in_class() and len(arg_types) < len(args):
                arg_types.insert(0, AnyType())
        else:
            arg_types = [a.type_annotation for a in args]
            return_type = TypeConverter(line=n.lineno).visit(n.returns)

        if isinstance(return_type, UnboundType):
            return_type.is_ret_type = True

        func_type = None
        if any(arg_types) or return_type:
            func_type = CallableType([a if a is not None else AnyType() for a in arg_types],
                                     arg_kinds,
                                     arg_names,
                                     return_type if return_type is not None else AnyType(),
                                     None)

        func_def = FuncDef(n.name,
                       args,
                       self.as_block(n.body, n.lineno),
                       func_type)
        if func_type is not None:
            func_type.definition = func_def
            func_type.line = n.lineno

        if n.decorator_list:
            var = Var(func_def.name())
            var.is_ready = False
            var.set_line(n.decorator_list[0].lineno)

            func_def.is_decorated = True
            func_def.set_line(n.lineno + len(n.decorator_list))
            func_def.body.set_line(func_def.get_line())
            return Decorator(func_def, self.visit_list(n.decorator_list), var)
        else:
            return func_def
开发者ID:danielfranca,项目名称:mypy,代码行数:59,代码来源:fastparse.py


示例6: visit_callable_type

 def visit_callable_type(self, t: CallableType) -> Type:
     if isinstance(self.s, CallableType) and is_similar_callables(
             t, cast(CallableType, self.s)):
         return combine_similar_callables(t, cast(CallableType, self.s))
     elif t.is_type_obj() and is_subtype(self.s, t.fallback):
         return t.fallback
     elif (t.is_type_obj() and isinstance(self.s, Instance) and
           cast(Instance, self.s).type == t.fallback):
         return t.fallback
     else:
         return self.default(self.s)
开发者ID:JamesTFarrington,项目名称:mypy,代码行数:11,代码来源:join.py


示例7: infer_function_type_arguments

def infer_function_type_arguments(callee_type: CallableType,
                                  arg_types: List[Optional[Type]],
                                  arg_kinds: List[int],
                                  formal_to_actual: List[List[int]],
                                  strict: bool = True) -> List[Type]:
    """Infer the type arguments of a generic function.

    Return an array of lower bound types for the type variables -1 (at
    index 0), -2 (at index 1), etc. A lower bound is None if a value
    could not be inferred.

    Arguments:
      callee_type: the target generic function
      arg_types: argument types at the call site (each optional; if None,
                 we are not considering this argument in the current pass)
      arg_kinds: nodes.ARG_* values for arg_types
      formal_to_actual: mapping from formal to actual variable indices
    """
    # Infer constraints.
    constraints = infer_constraints_for_callable(
        callee_type, arg_types, arg_kinds, formal_to_actual)

    # Solve constraints.
    type_vars = callee_type.type_var_ids()
    return solve_constraints(type_vars, constraints, strict)
开发者ID:ChaiYuanUMN,项目名称:mypy,代码行数:25,代码来源:infer.py


示例8: visit_callable_type

 def visit_callable_type(self, t: CallableType) -> Type:
     return t.copy_modified(
         arg_types=self.anal_array(t.arg_types),
         ret_type=t.ret_type.accept(self),
         fallback=t.fallback or self.builtin_type("builtins.function"),
         variables=self.anal_var_defs(t.variables),
     )
开发者ID:matthiaskramm,项目名称:mypy,代码行数:7,代码来源:typeanal.py


示例9: get_guesses

    def get_guesses(self, is_method: bool, base: CallableType, defaults: List[Optional[Type]],
                    callsites: List[Callsite]) -> List[CallableType]:
        """Compute a list of guesses for a function's type.

        This focuses just on the argument types, and doesn't change the provided return type.
        """
        options = self.get_args(is_method, base, defaults, callsites)
        return [base.copy_modified(arg_types=list(x)) for x in itertools.product(*options)]
开发者ID:Michael0x2a,项目名称:mypy,代码行数:8,代码来源:suggestions.py


示例10: is_callable_subtype

def is_callable_subtype(left: CallableType, right: CallableType,
                        ignore_return: bool = False) -> bool:
    """Is left a subtype of right?"""
    # TODO: Support named arguments, **args, etc.
    # Non-type cannot be a subtype of type.
    if right.is_type_obj() and not left.is_type_obj():
        return False

    # A callable L is a subtype of a generic callable R if L is a
    # subtype of every type obtained from R by substituting types for
    # the variables of R. We can check this by simply leaving the
    # generic variables of R as type variables, effectively varying
    # over all possible values.

    # It's okay even if these variables share ids with generic
    # type variables of L, because generating and solving
    # constraints for the variables of L to make L a subtype of R
    # (below) treats type variables on the two sides as independent.

    if left.variables:
        # Apply generic type variables away in left via type inference.
        left = unify_generic_callable(left, right, ignore_return=ignore_return)
        if left is None:
            return False

    # Check return types.
    if not ignore_return and not is_subtype(left.ret_type, right.ret_type):
        return False

    if right.is_ellipsis_args:
        return True

    # Check argument types.
    if left.min_args > right.min_args:
        return False
    if left.is_var_arg:
        return is_var_arg_callable_subtype_helper(left, right)
    if right.is_var_arg:
        return False
    if len(left.arg_types) < len(right.arg_types):
        return False
    for i in range(len(right.arg_types)):
        if not is_subtype(right.arg_types[i], left.arg_types[i]):
            return False
    return True
开发者ID:bdarnell,项目名称:mypy,代码行数:45,代码来源:subtypes.py


示例11: visit_callable_type

 def visit_callable_type(self, typ: CallableType) -> SnapshotItem:
     # FIX generics
     return ('CallableType',
             snapshot_types(typ.arg_types),
             snapshot_type(typ.ret_type),
             tuple(typ.arg_names),
             tuple(typ.arg_kinds),
             typ.is_type_obj(),
             typ.is_ellipsis_args)
开发者ID:greatmazinger,项目名称:mypy,代码行数:9,代码来源:astdiff.py


示例12: visit_FunctionDef

    def visit_FunctionDef(self, n):
        args = self.transform_args(n.args, n.lineno)

        arg_kinds = [arg.kind for arg in args]
        arg_names = [arg.variable.name() for arg in args]
        if n.type_comment is not None:
            func_type_ast = typed_ast.parse(n.type_comment, '<func_type>', 'func_type')
            arg_types = [a if a is not None else AnyType() for
                         a in TypeConverter(line=n.lineno).visit(func_type_ast.argtypes)]
            return_type = TypeConverter(line=n.lineno).visit(func_type_ast.returns)

            # add implicit self type
            if self.in_class and len(arg_types) < len(args):
                arg_types.insert(0, AnyType())
        else:
            arg_types = [a.type_annotation for a in args]
            return_type = TypeConverter(line=n.lineno).visit(n.returns)

        func_type = None
        if any(arg_types) or return_type:
            func_type = CallableType([a if a is not None else AnyType() for a in arg_types],
                                     arg_kinds,
                                     arg_names,
                                     return_type if return_type is not None else AnyType(),
                                     None)

        func_def = FuncDef(n.name,
                       args,
                       self.as_block(n.body, n.lineno),
                       func_type)
        if func_type is not None:
            func_type.definition = func_def

        if n.decorator_list:
            var = Var(func_def.name())
            var.is_ready = False
            var.set_line(n.decorator_list[0].lineno)

            func_def.is_decorated = True
            func_def.set_line(n.lineno + len(n.decorator_list))
            func_def.body.set_line(func_def.get_line())
            return Decorator(func_def, self.visit(n.decorator_list), var)
        else:
            return func_def
开发者ID:allthedata,项目名称:mypy,代码行数:44,代码来源:fastparse.py


示例13: apply_generic_arguments

def apply_generic_arguments(callable: CallableType, types: List[Type],
                            msg: MessageBuilder, context: Context) -> Type:
    """Apply generic type arguments to a callable type.

    For example, applying [int] to 'def [T] (T) -> T' results in
    'def (int) -> int'.

    Note that each type can be None; in this case, it will not be applied.
    """
    tvars = callable.variables
    if len(tvars) != len(types):
        msg.incompatible_type_application(len(tvars), len(types), context)
        return AnyType()

    # Check that inferred type variable values are compatible with allowed
    # values and bounds.  Also, promote subtype values to allowed values.
    types = types[:]
    for i, type in enumerate(types):
        values = callable.variables[i].values
        if values and type:
            if isinstance(type, AnyType):
                continue
            if isinstance(type, TypeVarType) and type.values:
                # Allow substituting T1 for T if every allowed value of T1
                # is also a legal value of T.
                if all(any(is_same_type(v, v1) for v in values)
                       for v1 in type.values):
                    continue
            for value in values:
                if mypy.subtypes.is_subtype(type, value):
                    types[i] = value
                    break
            else:
                msg.incompatible_typevar_value(callable, i + 1, type, context)

        upper_bound = callable.variables[i].upper_bound
        if type and not mypy.subtypes.satisfies_upper_bound(type, upper_bound):
            msg.incompatible_typevar_value(callable, i + 1, type, context)

    # Create a map from type variable id to target type.
    id_to_type = {}  # type: Dict[TypeVarId, Type]
    for i, tv in enumerate(tvars):
        if types[i]:
            id_to_type[tv.id] = types[i]

    # Apply arguments to argument types.
    arg_types = [expand_type(at, id_to_type) for at in callable.arg_types]

    # The callable may retain some type vars if only some were applied.
    remaining_tvars = [tv for tv in tvars if tv.id not in id_to_type]

    return callable.copy_modified(
        arg_types=arg_types,
        ret_type=expand_type(callable.ret_type, id_to_type),
        variables=remaining_tvars,
    )
开发者ID:AXGKl,项目名称:Transcrypt,代码行数:56,代码来源:applytype.py


示例14: analyze_callable_type

 def analyze_callable_type(self, t: UnboundType) -> Type:
     fallback = self.named_type('builtins.function')
     if len(t.args) == 0:
         # Callable (bare). Treat as Callable[..., Any].
         any_type = AnyType(TypeOfAny.from_omitted_generics,
                            line=t.line, column=t.column)
         ret = CallableType([any_type, any_type],
                            [nodes.ARG_STAR, nodes.ARG_STAR2],
                            [None, None],
                            ret_type=any_type,
                            fallback=fallback,
                            is_ellipsis_args=True)
     elif len(t.args) == 2:
         ret_type = t.args[1]
         if isinstance(t.args[0], TypeList):
             # Callable[[ARG, ...], RET] (ordinary callable type)
             analyzed_args = self.analyze_callable_args(t.args[0])
             if analyzed_args is None:
                 return AnyType(TypeOfAny.from_error)
             args, kinds, names = analyzed_args
             ret = CallableType(args,
                                kinds,
                                names,
                                ret_type=ret_type,
                                fallback=fallback)
         elif isinstance(t.args[0], EllipsisType):
             # Callable[..., RET] (with literal ellipsis; accept arbitrary arguments)
             ret = CallableType([AnyType(TypeOfAny.explicit),
                                 AnyType(TypeOfAny.explicit)],
                                [nodes.ARG_STAR, nodes.ARG_STAR2],
                                [None, None],
                                ret_type=ret_type,
                                fallback=fallback,
                                is_ellipsis_args=True)
         else:
             self.fail('The first argument to Callable must be a list of types or "..."', t)
             return AnyType(TypeOfAny.from_error)
     else:
         self.fail('Please use "Callable[[<parameters>], <return type>]" or "Callable"', t)
         return AnyType(TypeOfAny.from_error)
     assert isinstance(ret, CallableType)
     return ret.accept(self)
开发者ID:greatmazinger,项目名称:mypy,代码行数:42,代码来源:typeanal.py


示例15: visit_callable_type

 def visit_callable_type(self, left: CallableType) -> bool:
     # FIX generics
     if isinstance(self.right, CallableType):
         cright = cast(CallableType, self.right)
         return (is_same_type(left.ret_type, cright.ret_type) and
                 is_same_types(left.arg_types, cright.arg_types) and
                 left.arg_names == cright.arg_names and
                 left.arg_kinds == cright.arg_kinds and
                 left.is_type_obj() == cright.is_type_obj())
     else:
         return False
开发者ID:JamesTFarrington,项目名称:mypy,代码行数:11,代码来源:sametypes.py


示例16: visit_callable_type

 def visit_callable_type(self, t: CallableType) -> Type:
     if isinstance(self.s, CallableType) and is_similar_callables(t, self.s):
         if is_equivalent(t, self.s):
             return combine_similar_callables(t, self.s)
         result = meet_similar_callables(t, self.s)
         if isinstance(result.ret_type, UninhabitedType):
             # Return a plain None or <uninhabited> instead of a weird function.
             return self.default(self.s)
         return result
     elif isinstance(self.s, TypeType) and t.is_type_obj() and not t.is_generic():
         # In this case we are able to potentially produce a better meet.
         res = meet_types(self.s.item, t.ret_type)
         if not isinstance(res, (NoneType, UninhabitedType)):
             return TypeType.make_normalized(res)
         return self.default(self.s)
     elif isinstance(self.s, Instance) and self.s.type.is_protocol:
         call = unpack_callback_protocol(self.s)
         if call:
             return meet_types(t, call)
     return self.default(self.s)
开发者ID:python,项目名称:mypy,代码行数:20,代码来源:meet.py


示例17: visit_callable_type

 def visit_callable_type(self, t: CallableType, nested: bool = True) -> Type:
     # Every Callable can bind its own type variables, if they're not in the outer scope
     with self.tvar_scope_frame():
         if self.aliasing:
             variables = t.variables
         else:
             variables = self.bind_function_type_variables(t, t)
         ret = t.copy_modified(arg_types=self.anal_array(t.arg_types, nested=nested),
                               ret_type=self.anal_type(t.ret_type, nested=nested),
                               fallback=t.fallback or self.named_type('builtins.function'),
                               variables=self.anal_var_defs(variables))
     return ret
开发者ID:greatmazinger,项目名称:mypy,代码行数:12,代码来源:typeanal.py


示例18: visit_callable_type

 def visit_callable_type(self, typ: CallableType) -> None:
     for arg in typ.arg_types:
         arg.accept(self)
     typ.ret_type.accept(self)
     if typ.definition:
         # No need to fixup since this is just a cross-reference.
         typ.definition = self.replacements.get(typ.definition, typ.definition)
     # TODO: typ.fallback
     for tv in typ.variables:
         tv.upper_bound.accept(self)
         for value in tv.values:
             value.accept(self)
开发者ID:greatmazinger,项目名称:mypy,代码行数:12,代码来源:astmerge.py


示例19: class_callable

def class_callable(init_type: CallableType, info: TypeInfo, type_type: Instance,
                   special_sig: Optional[str]) -> CallableType:
    """Create a type object type based on the signature of __init__."""
    variables = []  # type: List[TypeVarDef]
    variables.extend(info.defn.type_vars)
    variables.extend(init_type.variables)

    callable_type = init_type.copy_modified(
        ret_type=fill_typevars(info), fallback=type_type, name=None, variables=variables,
        special_sig=special_sig)
    c = callable_type.with_name(info.name())
    return c
开发者ID:Michael0x2a,项目名称:mypy,代码行数:12,代码来源:checkmember.py


示例20: visit_callable_type

 def visit_callable_type(self, t: CallableType) -> Type:
     if self.check_recursion(t):
         return AnyType(TypeOfAny.from_error)
     arg_types = [tp.accept(self) for tp in t.arg_types]
     ret_type = t.ret_type.accept(self)
     variables = t.variables.copy()
     for v in variables:
         if v.upper_bound:
             v.upper_bound = v.upper_bound.accept(self)
         if v.values:
             v.values = [val.accept(self) for val in v.values]
     return t.copy_modified(arg_types=arg_types, ret_type=ret_type, variables=variables)
开发者ID:sixolet,项目名称:mypy,代码行数:12,代码来源:semanal_pass3.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python types.Instance类代码示例发布时间:2022-05-27
下一篇:
Python types.is_named_instance函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap