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


Python FuncDef.type方法代码示例

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


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

示例1: add_method

# 需要导入模块: from mypy.nodes import FuncDef [as 别名]
# 或者: from mypy.nodes.FuncDef import type [as 别名]
    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,代码行数:31,代码来源:attrs.py

示例2: visit_func_def

# 需要导入模块: from mypy.nodes import FuncDef [as 别名]
# 或者: from mypy.nodes.FuncDef import type [as 别名]
 def visit_func_def(self, node: FuncDef) -> None:
     if not self.recurse_into_functions:
         return
     node.expanded = []
     node.type = node.unanalyzed_type
     with self.enter_method(node.info) if node.info else nothing():
         super().visit_func_def(node)
开发者ID:greatmazinger,项目名称:mypy,代码行数:9,代码来源:aststrip.py

示例3: add_method

# 需要导入模块: from mypy.nodes import FuncDef [as 别名]
# 或者: from mypy.nodes.FuncDef import type [as 别名]
        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,代码行数:36,代码来源:semanal_namedtuple.py

示例4: add_method

# 需要导入模块: from mypy.nodes import FuncDef [as 别名]
# 或者: from mypy.nodes.FuncDef import type [as 别名]
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,代码行数:36,代码来源:common.py

示例5: visit_func_def

# 需要导入模块: from mypy.nodes import FuncDef [as 别名]
# 或者: from mypy.nodes.FuncDef import type [as 别名]
 def visit_func_def(self, node: FuncDef) -> None:
     if not self.recurse_into_functions:
         return
     node.expanded = []
     node.type = node.unanalyzed_type
     # Type variable binder binds tvars before the type is analyzed.
     # It should be refactored, before that we just undo this change here.
     # TODO: this will be not necessary when #4814 is fixed.
     if node.type:
         assert isinstance(node.type, CallableType)
         node.type.variables = []
     with self.enter_method(node.info) if node.info else nothing():
         super().visit_func_def(node)
开发者ID:Michael0x2a,项目名称:mypy,代码行数:15,代码来源:aststrip.py

示例6: prepend_generic_function_tvar_args

# 需要导入模块: from mypy.nodes import FuncDef [as 别名]
# 或者: from mypy.nodes.FuncDef import type [as 别名]
    def prepend_generic_function_tvar_args(self, fdef: FuncDef) -> None:
        """Add implicit function type variable arguments if fdef is generic."""
        sig = cast(Callable, function_type(fdef))
        tvars = sig.variables
        if not fdef.type:
            fdef.type = sig

        tv = []  # type: List[Var]
        ntvars = len(tvars)
        if fdef.is_method():
            # For methods, add type variable arguments after the self arg.
            for n in range(ntvars):
                tv.append(Var(tvar_arg_name(-1 - n)))
                fdef.type = add_arg_type_after_self(cast(Callable, fdef.type), AnyType())
            fdef.args = [fdef.args[0]] + tv + fdef.args[1:]
        else:
            # For ordinary functions, prepend type variable arguments.
            for n in range(ntvars):
                tv.append(Var(tvar_arg_name(-1 - n)))
                fdef.type = prepend_arg_type(cast(Callable, fdef.type), AnyType())
            fdef.args = tv + fdef.args
        fdef.init = List[AssignmentStmt]([None]) * ntvars + fdef.init
开发者ID:ashleyh,项目名称:mypy,代码行数:24,代码来源:transform.py

示例7: make_type_object_wrapper

# 需要导入模块: from mypy.nodes import FuncDef [as 别名]
# 或者: from mypy.nodes.FuncDef import type [as 别名]
    def make_type_object_wrapper(self, tdef):
        """Construct dynamically typed wrapper function for a class.

        It simple calls the type object and returns the result.
        """
        
        # TODO keyword args, default args and varargs
        # TODO overloads

        type_sig = type_object_type(tdef.info, None)
        type_sig = erasetype.erase_typevars(type_sig)
        
        init = tdef.info.get_method('__init__')
        arg_kinds = type_sig.arg_kinds

        # The wrapper function has a dynamically typed signature.
        wrapper_sig = Callable( [Any()] * len(arg_kinds),
                               arg_kinds, [None] * len(arg_kinds),
                               Any(), False)
        
        n = NameExpr(tdef.name) # TODO full name
        args = self.func_tf.call_args(
            init.args[1:],
            type_sig,
            wrapper_sig,
            True, False)
        call = CallExpr(n, args, arg_kinds)
        ret = ReturnStmt(call)
        

        fdef = FuncDef(tdef.name + self.tf.dynamic_suffix(),
                       init.args[1:],
                       arg_kinds, [None] * len(arg_kinds),
                       Block([ret]))
        
        fdef.type = wrapper_sig
        return fdef
开发者ID:SRiikonen,项目名称:mypy-py,代码行数:39,代码来源:transformtype.py

示例8: make_init_wrapper

# 需要导入模块: from mypy.nodes import FuncDef [as 别名]
# 或者: from mypy.nodes.FuncDef import type [as 别名]
    def make_init_wrapper(self, tdef):
        """Make and return an implicit __init__ if class needs it.
        
        Otherwise, return an empty list. We include an implicit
        __init__ if the class is generic or if it extends a generic class
        and if it does not define __init__.
        
        The __init__ of a generic class requires one or more extra type
        variable arguments. The inherited __init__ may not accept these.

        For example, assume these definitions:
        
        . class A<T>: pass
        . class B(A<int>): pass
        
        The constructor for B will be (equivalent to)
        
        . void __init__(B self):
        .     self.__tv = <int>
        .     super().__init__(<int>)
        """
        
        # FIX overloading, default args / varargs, keyword args

        info = tdef.info
        
        if '__init__' not in info.methods and (
                tdef.is_generic() or (info.base and info.base.is_generic())):
            # Generic class with no explicit __init__ method
            # (i.e. __init__ inherited from superclass). Generate a
            # wrapper that initializes type variable slots and calls
            # the superclass __init__ method.
            
            selftype = self_type(info)    
            callee_type = analyse_member_access(
                '__init__', selftype, None, False, True, None, None,
                info.base)
            
            # Now the callee type may contain the type variables of a
            # grandparent as bound type variables, but we want the
            # type variables of the parent class. Explicitly set the
            # bound type variables.
            callee_type = self.fix_bound_init_tvars(callee_type,
                map_instance_to_supertype(selftype, info.base))
            
            super_init = info.base.get_method('__init__')
            
            # Build argument list.
            args = [Var('self')]
            for i in range(1, len(super_init.args)):
                args.append(Var(super_init.args[i].name()))
                args[-1].type = callee_type.arg_types[i - 1]

            selft = self_type(self.tf.type_context())
            callee_type = prepend_arg_type(callee_type, selft)
            
            creat = FuncDef('__init__', args,
                            super_init.arg_kinds, [None] * len(args),
                            Block([]))
            creat.info = tdef.info
            creat.type = callee_type
            creat.is_implicit = False
            tdef.info.methods['__init__'] = creat
            
            # Insert a call to superclass constructor. If the
            # superclass is object, the constructor does nothing =>
            # omit the call.
            if tdef.info.base.full_name() != 'builtins.object':
                creat.body.body.append(
                    self.make_superclass_constructor_call(tdef.info,
                                                          callee_type))
            
            # Implicit cast from FuncDef[] to Node[] is safe below.
            return self.func_tf.transform_method(creat)
        else:
            return []
开发者ID:SRiikonen,项目名称:mypy-py,代码行数:78,代码来源:transformtype.py

示例9: range

# 需要导入模块: from mypy.nodes import FuncDef [as 别名]
# 或者: from mypy.nodes.FuncDef import type [as 别名]
            
            # Build argument list.
            args = [Var('self')]
            for i in range(1, len(super_init.args)):
                args.append(Var(super_init.args[i].name()))
                args[-1].type = callee_type.arg_types[i - 1]

            selft = self_type(self.tf.type_context())
            callee_type = prepend_arg_type(callee_type, selft)
            
            creat = FuncDef('__init__', args,
                            super_init.arg_kinds,
                            <Node> [None] * len(args),
                            Block([]))
            creat.info = tdef.info
            creat.type = callee_type
            creat.is_implicit = False
            tdef.info.methods['__init__'] = creat
            
            # Insert a call to superclass constructor. If the
            # superclass is object, the constructor does nothing =>
            # omit the call.
            if tdef.info.base.full_name() != 'builtins.object':
                creat.body.body.append(
                    self.make_superclass_constructor_call(tdef.info,
                                                          callee_type))
            
            # Implicit cast from FuncDef[] to Node[] is safe below.
            return (any)self.func_tf.transform_method(creat)
        else:
            return []
开发者ID:SRiikonen,项目名称:mypy,代码行数:33,代码来源:transformtype.py


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