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

Python nodes.FuncDef类代码示例

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

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



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

示例1: 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


示例2: 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


示例3: 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


示例4: visit_func_def

 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,代码行数:7,代码来源:aststrip.py


示例5: make_setter_wrapper

    def make_setter_wrapper(self, name, typ):
        """Create a setter wrapper for a data attribute.

        The setter will be of this form:
        
        . void set$name(C self, typ name):
        .     self.name! = name
        """
        scope = self.make_scope()
        selft = self.self_type()
        selfv = scope.add('self', selft)
        namev = scope.add(name, typ)
        
        lvalue = MemberExpr(scope.name_expr('self'), name, direct=True)
        rvalue = scope.name_expr(name)
        ret = AssignmentStmt([lvalue], rvalue)

        wrapper_name = 'set$' + name
        sig = Callable([selft, typ],
                       [nodes.ARG_POS, nodes.ARG_POS],
                       [None, None],
                       Void(), False)
        fdef = FuncDef(wrapper_name,
                       [selfv, namev],
                       [nodes.ARG_POS, nodes.ARG_POS],
                       [None, None],
                       Block([ret]), sig)
        fdef.info = self.tf.type_context()
        return fdef
开发者ID:SRiikonen,项目名称:mypy-py,代码行数:29,代码来源:transformtype.py


示例6: visit_func_def

 def visit_func_def(self, o: FuncDef) -> None:
     if self.is_private_name(o.name()):
         return
     if self.is_not_in_all(o.name()):
         return
     if self.is_recorded_name(o.name()):
         return
     if not self._indent and self._state not in (EMPTY, FUNC):
         self.add('\n')
     if not self.is_top_level():
         self_inits = find_self_initializers(o)
         for init in self_inits:
             init_code = self.get_init(init)
             if init_code:
                 self.add(init_code)
     self.add("%sdef %s(" % (self._indent, o.name()))
     self.record_name(o.name())
     args = []  # type: List[str]
     for i, arg_ in enumerate(o.arguments):
         var = arg_.variable
         kind = arg_.kind
         name = var.name()
         init_stmt = arg_.initialization_statement
         if init_stmt:
             if kind == ARG_NAMED and '*' not in args:
                 args.append('*')
             arg = '%s=' % name
             rvalue = init_stmt.rvalue
             if isinstance(rvalue, IntExpr):
                 arg += str(rvalue.value)
             elif isinstance(rvalue, StrExpr):
                 arg += "''"
             elif isinstance(rvalue, BytesExpr):
                 arg += "b''"
             elif isinstance(rvalue, FloatExpr):
                 arg += "0.0"
             elif isinstance(rvalue, UnaryExpr) and isinstance(rvalue.expr, IntExpr):
                 arg += '-%s' % rvalue.expr.value
             elif isinstance(rvalue, NameExpr) and rvalue.name in ('None', 'True', 'False'):
                 arg += rvalue.name
             else:
                 arg += '...'
         elif kind == ARG_STAR:
             arg = '*%s' % name
         elif kind == ARG_STAR2:
             arg = '**%s' % name
         else:
             arg = name
         args.append(arg)
     self.add(', '.join(args))
     self.add("): ...\n")
     self._state = FUNC
开发者ID:axitkhurana,项目名称:mypy,代码行数:52,代码来源:stubgen.py


示例7: visit_func_def

 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,代码行数:13,代码来源:aststrip.py


示例8: visit_func_def

 def visit_func_def(self, func: FuncDef) -> None:
     sem = self.sem
     if sem.type is not None:
         # Don't process methods during pass 1.
         return
     func.is_conditional = sem.block_depth[-1] > 0
     func._fullname = sem.qualified_name(func.name())
     at_module = sem.is_module_scope()
     if at_module and func.name() in sem.globals:
         # Already defined in this module.
         original_sym = sem.globals[func.name()]
         if original_sym.kind == UNBOUND_IMPORTED:
             # Ah this is an imported name. We can't resolve them now, so we'll postpone
             # this until the main phase of semantic analysis.
             return
         if not sem.set_original_def(original_sym.node, func):
             # Report error.
             sem.check_no_global(func.name(), func)
     else:
         if at_module:
             sem.globals[func.name()] = SymbolTableNode(GDEF, func)
         # Also analyze the function body (needed in case there are unreachable
         # conditional imports).
         sem.function_stack.append(func)
         sem.errors.push_function(func.name())
         sem.enter()
         func.body.accept(self)
         sem.leave()
         sem.errors.pop_function()
         sem.function_stack.pop()
开发者ID:greatmazinger,项目名称:mypy,代码行数:30,代码来源:semanal_pass1.py


示例9: set_callable_name

def set_callable_name(sig: Type, fdef: FuncDef) -> Type:
    if isinstance(sig, FunctionLike):
        if fdef.info:
            if fdef.info.fullname() in TPDICT_FB_NAMES:
                # Avoid exposing the internal _TypedDict name.
                class_name = 'TypedDict'
            else:
                class_name = fdef.info.name()
            return sig.with_name(
                '{} of {}'.format(fdef.name(), class_name))
        else:
            return sig.with_name(fdef.name())
    else:
        return sig
开发者ID:python,项目名称:mypy,代码行数:14,代码来源:semanal_shared.py


示例10: make_generic_wrapper_init

    def make_generic_wrapper_init(self, info: TypeInfo) -> FuncDef:
        """Build constructor of a generic wrapper class."""
        nslots = num_slots(info)
        
        cdefs = [] # type: List[Node]
        
        # Build superclass constructor call.
        base = info.mro[1]
        if base.fullname() != 'builtins.object' and self.tf.is_java:
            s = SuperExpr('__init__')
            cargs = [NameExpr('__o')] # type: List[Node]
            for n in range(num_slots(base)):
                cargs.append(NameExpr(tvar_arg_name(n + 1)))
            for n in range(num_slots(base)):
                cargs.append(NameExpr(tvar_arg_name(n + 1, BOUND_VAR)))
            c = CallExpr(s, cargs, [nodes.ARG_POS] * len(cargs))
            cdefs.append(ExpressionStmt(c))
        
        # Create initialization of the wrapped object.
        cdefs.append(AssignmentStmt([MemberExpr(
                                         self_expr(),
                                         self.object_member_name(info),
                                         direct=True)],
                                    NameExpr('__o')))
        
        # Build constructor arguments.
        args = [Var('self'), Var('__o')]
        init = [None, None] # type: List[Node]
        
        for alt in [False, BOUND_VAR]:
            for n in range(nslots):
                args.append(Var(tvar_arg_name(n + 1, alt)))
                init.append(None)

        nargs = nslots * 2 + 2
        fdef = FuncDef('__init__',
                       args,
                       [nodes.ARG_POS] * nargs,
                       init,
                       Block(cdefs),
                       Callable( [AnyType()] * nargs,
                                [nodes.ARG_POS] * nargs, [None] * nargs,
                                Void(),
                                is_type_obj=False))
        fdef.info = info
        
        self.make_wrapper_slot_initializer(fdef)
        
        return fdef
开发者ID:FlorianLudwig,项目名称:mypy,代码行数:49,代码来源:transformtype.py


示例11: visit_func_def

 def visit_func_def(self, fdef: FuncDef) -> None:
     if not self.recurse_into_functions:
         return
     self.errors.push_function(fdef.name())
     self.analyze(fdef.type, fdef)
     super().visit_func_def(fdef)
     self.errors.pop_function()
开发者ID:greatmazinger,项目名称:mypy,代码行数:7,代码来源:semanal_pass3.py


示例12: visit_func_def

    def visit_func_def(self, defn: FuncDef) -> None:
        start_line = defn.get_line() - 1
        start_indent = self.indentation_level(start_line)
        cur_line = start_line + 1
        end_line = cur_line
        # After this loop, function body will be lines [start_line, end_line)
        while cur_line < len(self.source):
            cur_indent = self.indentation_level(cur_line)
            if cur_indent is None:
                # Consume the line, but don't mark it as belonging to the function yet.
                cur_line += 1
            elif cur_indent > start_indent:
                # A non-blank line that belongs to the function.
                cur_line += 1
                end_line = cur_line
            else:
                # We reached a line outside the function definition.
                break

        is_typed = defn.type is not None
        for line in range(start_line, end_line):
            old_indent, _ = self.lines_covered[line]
            assert start_indent > old_indent
            self.lines_covered[line] = (start_indent, is_typed)

        # Visit the body, in case there are nested functions
        super().visit_func_def(defn)
开发者ID:JdeH,项目名称:Transcrypt,代码行数:27,代码来源:report.py


示例13: enter_function_scope

 def enter_function_scope(self, fdef: FuncDef) -> str:
     """Enter a function target scope."""
     target = '%s.%s' % (self.full_target_stack[-1], fdef.name())
     self.target_stack.append(target)
     self.full_target_stack.append(target)
     self.scope_stack.append(fdef)
     return target
开发者ID:greatmazinger,项目名称:mypy,代码行数:7,代码来源:deps.py


示例14: visit_func_def

 def visit_func_def(self, func: FuncDef) -> None:
     if self.current_info is not None:
         func.info = self.current_info
     if func.type is not None:
         func.type.accept(self.type_fixer)
     for arg in func.arguments:
         if arg.type_annotation is not None:
             arg.type_annotation.accept(self.type_fixer)
开发者ID:qaphla,项目名称:mypy,代码行数:8,代码来源:fixup.py


示例15: try_type

    def try_type(self, func: FuncDef, typ: Type) -> List[str]:
        """Recheck a function while assuming it has type typ.

        Return all error messages.
        """
        old = func.unanalyzed_type
        # During reprocessing, unanalyzed_type gets copied to type (by aststrip).
        # We don't modify type because it isn't necessary and it
        # would mess up the snapshotting.
        func.unanalyzed_type = typ
        try:
            res = self.fgmanager.trigger(func.fullname())
            # if res:
            #     print('\n'.join(res))
            return res
        finally:
            func.unanalyzed_type = old
开发者ID:Michael0x2a,项目名称:mypy,代码行数:17,代码来源:suggestions.py


示例16: visit_func_def

    def visit_func_def(self, node: FuncDef) -> FuncDef:
        # Note that a FuncDef must be transformed to a FuncDef.
        new = FuncDef(node.name(),
                      [self.copy_argument(arg) for arg in node.arguments],
                      self.block(node.body),
                      cast(FunctionLike, self.optional_type(node.type)))

        self.copy_function_attributes(new, node)

        new._fullname = node._fullname
        new.is_decorated = node.is_decorated
        new.is_conditional = node.is_conditional
        new.is_abstract = node.is_abstract
        new.is_static = node.is_static
        new.is_class = node.is_class
        new.is_property = node.is_property
        new.original_def = node.original_def
        return new
开发者ID:the-gigi,项目名称:mypy,代码行数:18,代码来源:treetransform.py


示例17: transform_method_implementation

 def transform_method_implementation(self, fdef, name):
     """Transform the implementation of a method (i.e. unwrapped)."""
     args = fdef.args
     arg_kinds = fdef.arg_kinds
     
     typ = function_type(fdef)
     init = fdef.init_expressions()
     
     if fdef.name() == '__init__' and is_generic(fdef):
         args, arg_kinds, init, typ = self.add_constructor_tvar_args(
             fdef, typ, args, arg_kinds, init)
     
     fdef2 = FuncDef(name, args, arg_kinds, init, fdef.body, typ)
     fdef2.info = fdef.info
     
     self.tf.prepend_generic_function_tvar_args(fdef2)
     
     return fdef2
开发者ID:SRiikonen,项目名称:mypy-py,代码行数:18,代码来源:transformfunc.py


示例18: transform_method

    def transform_method(self, fdef: FuncDef) -> List[FuncDef]:
        """Transform a method.

        The result is one or more methods.
        """
        # Transform the body of the method.
        self.tf.transform_function_body(fdef)
        
        res = Undefined # type: List[FuncDef]
        
        if fdef.is_constructor():
            # The method is a constructor. Constructors are transformed to one
            # method.
            res = [self.transform_method_implementation(fdef, fdef.name())]
        else:
            # Normal methods are transformed to 1-3 variants. The
            # first is the main implementation of the method, and the
            # second is the dynamically-typed wrapper. The third
            # variant is for method overrides, and represents the
            # overridden supertype method.
            
            res = [self.transform_method_implementation(
                fdef, fdef.name() + self.tf.type_suffix(fdef))]
            
            if fdef.info.bases and fdef.info.mro[1].has_method(fdef.name()):
                # Override.
                # TODO do not assume single inheritance
                
                # Is is an override with a different signature? For
                # trivial overrides we can inherit wrappers.
                if not is_simple_override(fdef, fdef.info):
                    # Create a wrapper for overridden superclass method.
                    res.append(self.override_method_wrapper(fdef))
                    # Create a dynamically-typed method wrapper.
                    res.append(self.dynamic_method_wrapper(fdef))
            else:
                # Not an override.
                
                # Create a dynamically-typed method wrapper.
                res.append(self.dynamic_method_wrapper(fdef))
        
        return res
开发者ID:FlorianLudwig,项目名称:mypy,代码行数:42,代码来源:transformfunc.py


示例19: visit_func_def

    def visit_func_def(self, node: FuncDef) -> FuncDef:
        # Note that a FuncDef must be transformed to a FuncDef.
        new = FuncDef(node.name(),
                      [self.visit_var(var) for var in node.args],
                      node.arg_kinds[:],
                      [None] * len(node.init),
                      self.block(node.body),
                      self.optional_type(node.type))

        self.copy_function_attributes(new, node)

        new._fullname = node._fullname
        new.is_decorated = node.is_decorated
        new.is_conditional = node.is_conditional
        new.is_abstract = node.is_abstract
        new.is_static = node.is_static
        new.is_class = node.is_class
        new.is_property = node.is_property
        new.original_def = node.original_def
        return new
开发者ID:akaihola,项目名称:mypy,代码行数:20,代码来源:treetransform.py


示例20: build_newtype_typeinfo

    def build_newtype_typeinfo(self, name: str, old_type: Type, base_type: Instance) -> TypeInfo:
        info = self.api.basic_new_typeinfo(name, base_type)
        info.is_newtype = True

        # Add __init__ method
        args = [Argument(Var('self'), NoneTyp(), None, ARG_POS),
                self.make_argument('item', old_type)]
        signature = CallableType(
            arg_types=[Instance(info, []), old_type],
            arg_kinds=[arg.kind for arg in args],
            arg_names=['self', 'item'],
            ret_type=NoneTyp(),
            fallback=self.api.named_type('__builtins__.function'),
            name=name)
        init_func = FuncDef('__init__', args, Block([]), typ=signature)
        init_func.info = info
        init_func._fullname = self.api.qualified_name(name) + '.__init__'
        info.names['__init__'] = SymbolTableNode(MDEF, init_func)

        return info
开发者ID:mananpal1997,项目名称:mypy,代码行数:20,代码来源:semanal_newtype.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python nodes.MypyFile类代码示例发布时间:2022-05-27
下一篇:
Python nodes.ClassDef类代码示例发布时间: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