當前位置: 首頁>>代碼示例>>Python>>正文


Python ast.FunctionDef方法代碼示例

本文整理匯總了Python中ast.FunctionDef方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.FunctionDef方法的具體用法?Python ast.FunctionDef怎麽用?Python ast.FunctionDef使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ast的用法示例。


在下文中一共展示了ast.FunctionDef方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: indent_not_multiple_of_tab_size

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def indent_not_multiple_of_tab_size(project_folder, tab_size, *args, **kwargs):
    """
        Since there are cases for which col_offset is computed incorrectly,
        this validator must be nothing more than a simple warning.

        It compliments the pep8 validator which tends to fail in cases when
        the indent is incorrect.
    """
    node_types_to_validate = (ast.For, ast.If, ast.FunctionDef, ast.With)
    for parsed_file in project_folder.get_parsed_py_files():
        lines_offsets = file_helpers.get_line_offsets(parsed_file.content)
        for node in ast.walk(parsed_file.ast_tree):
            if not ast_helpers.is_node_offset_fine(
                node,
                lines_offsets,
                node_types_to_validate,
                tab_size,
            ):
                return parsed_file.get_name_with_line(node.lineno) 
開發者ID:devmanorg,項目名稱:fiasko_bro,代碼行數:21,代碼來源:syntax.py

示例2: CONTINUE

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def CONTINUE(self, node):
        # Walk the tree up until we see a loop (OK), a function or class
        # definition (not OK), for 'continue', a finally block (not OK), or
        # the top module scope (not OK)
        n = node
        while hasattr(n, 'parent'):
            n, n_child = n.parent, n
            if isinstance(n, LOOP_TYPES):
                # Doesn't apply unless it's in the loop itself
                if n_child not in n.orelse:
                    return
            if isinstance(n, (ast.FunctionDef, ast.ClassDef)):
                break
            # Handle Try/TryFinally difference in Python < and >= 3.3
            if hasattr(n, 'finalbody') and isinstance(node, ast.Continue):
                if n_child in n.finalbody:
                    self.report(messages.ContinueInFinally, node)
                    return
        if isinstance(node, ast.Continue):
            self.report(messages.ContinueOutsideLoop, node)
        else:  # ast.Break
            self.report(messages.BreakOutsideLoop, node) 
開發者ID:AtomLinter,項目名稱:linter-pylama,代碼行數:24,代碼來源:checker.py

示例3: _has_return

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def _has_return(fun):
    # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> bool
    """Return true if the function has a fruitful return.

    Args:
        fun: A function node to check.

    Returns:
        True if there is a fruitful return, otherwise False.

    """
    def skip(f):
        return f != fun and isinstance(f, FunctionDef)

    for node in _walk(fun, skip):
        if isinstance(node, ast.Return) and node.value is not None:
            return True
    return False 
開發者ID:terrencepreilly,項目名稱:darglint,代碼行數:20,代碼來源:function_description.py

示例4: _get_decorator_names

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def _get_decorator_names(fun):  # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> List[str]  # noqa: E501
    """Get decorator names from the function.

    Args:
        fun: The function whose decorators we are getting.

    Returns:
        The names of the decorators. Does not include setters and
        getters.

    """
    ret = list()
    for decorator in fun.decorator_list:
        # Attributes (setters and getters) won't have an id.
        if hasattr(decorator, 'id'):
            ret.append(getattr(decorator, 'id'))
    return ret 
開發者ID:terrencepreilly,項目名稱:darglint,代碼行數:19,代碼來源:function_description.py

示例5: get_line_number_from_function

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def get_line_number_from_function(fn):
    # type: (Union[ast.FunctionDef, ast.AsyncFunctionDef]) -> int
    """Get the line number for the end of the function signature.

    The function signature can be farther down when the parameter
    list is split across multiple lines.

    Args:
        fn: The function from which we are getting the line number.

    Returns:
        The line number for the start of the docstring for this
        function.

    """
    line_number = fn.lineno
    if hasattr(fn, 'args') and fn.args.args:
        last_arg = fn.args.args[-1]
        line_number = last_arg.lineno
    return line_number 
開發者ID:terrencepreilly,項目名稱:darglint,代碼行數:22,代碼來源:function_description.py

示例6: _find_sub_setup_call

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def _find_sub_setup_call(
        self, elements
    ):  # type: (List[Any]) -> Tuple[Optional[ast.Call], Optional[List[Any]]]
        for element in elements:
            if not isinstance(element, (ast.FunctionDef, ast.If)):
                continue

            setup_call = self._find_setup_call(element.body)
            if setup_call != (None, None):
                setup_call, body = setup_call

                body = elements + body

                return setup_call, body

        return None, None 
開發者ID:python-poetry,項目名稱:poetry,代碼行數:18,代碼來源:setup_reader.py

示例7: __init__

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def __init__(self,
                 symbol_table: SymbolTable,
                 custom_types_symbol_table: SymbolTable,
                 external_ir2_symbols_by_name_by_module: Dict[str, Dict[str, Union[ir2.FunctionDefn, ir2.CustomType]]],
                 filename: str,
                 source_lines: List[str],
                 identifier_generator: Iterator[str],
                 function_name: Optional[str] = None,
                 function_definition_line: Optional[int] = None,
                 first_enclosing_except_stmt_line: Optional[int] = None,
                 partially_typechecked_function_definitions_by_name: Dict[str, ast.FunctionDef] = None):
        assert (function_name is None) == (function_definition_line is None)
        self.symbol_table = symbol_table
        self.custom_types_symbol_table = custom_types_symbol_table
        self.external_ir2_symbols_by_name_by_module = external_ir2_symbols_by_name_by_module
        self.partially_typechecked_function_definitions_by_name = partially_typechecked_function_definitions_by_name or dict()
        self.filename = filename
        self.source_lines = source_lines
        self.current_function_name = function_name
        self.current_function_definition_line = function_definition_line
        self.first_enclosing_except_stmt_line = first_enclosing_except_stmt_line
        self.identifier_generator = identifier_generator 
開發者ID:google,項目名稱:tmppy,代碼行數:24,代碼來源:_ast_to_ir2.py

示例8: format_variables

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def format_variables(self, event, last_statement):
        if last_statement:
            last_source_line = event.source.lines[last_statement.lineno - 1]
            dots = (get_leading_spaces(last_source_line)
                    .replace(' ', '.')
                    .replace('\t', '....'))
        else:
            dots = ''
            last_source_line = ''
        lines = []
        for var in event.variables:
            if (u'{} = {}'.format(*var) != last_source_line.strip()
                    and not (
                            isinstance(last_statement, ast.FunctionDef)
                            and not last_statement.decorator_list
                            and var[0] == last_statement.name
                    )
            ):
                lines += self.format_variable(var, dots, event.comprehension_type)
        return lines 
開發者ID:alexmojaki,項目名稱:snoop,代碼行數:22,代碼來源:formatting.py

示例9: get_source

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def get_source(self):
        """
        Get a string containing the Python source code corresponding to the
        statements in the block.

        Returns:
            A string containing the source code of the statements.
        """
        src = ""
        for statement in self.statements:
            if type(statement) in [ast.If, ast.For, ast.While]:
                src += (astor.to_source(statement)).split('\n')[0] + "\n"
            elif type(statement) == ast.FunctionDef or\
                 type(statement) == ast.AsyncFunctionDef:
                src += (astor.to_source(statement)).split('\n')[0] + "...\n"
            else:
                src += astor.to_source(statement)
        return src 
開發者ID:coetaur0,項目名稱:staticfg,代碼行數:20,代碼來源:model.py

示例10: find_func

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def find_func(module, namespace):
    """Filter away everything except the function

    Addionally rename the function for better readability.

    Args:
        module (ast.Module): the entire parsed code
        namespace (str): identifier for the function of interest

    `namspace` will be of the form <module_name>.<function_name>

    Returns:
        module (ast.Module): the original module but with everything filtered
        away except the function and the function with a more readable name

    """
    module_name, func_name = namespace.split('.')
    funcs = [stmt for stmt in module.body if isinstance(stmt, ast.FunctionDef)]
    func, = [func for func in funcs if func.name == func_name]
    func.name = f'{module_name}.{func_name}'
    module.body = [func]
    return module 
開發者ID:ebanner,項目名稱:pynt,代碼行數:24,代碼來源:syntax.py

示例11: find_method

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def find_method(module, namespace):
    """Filter away everything except the method

    Promote the method up to the global namespace so that it is
    indistinguishable from a regular function.

    Arguments:
        module (ast.Module): the entire parsed source code
        namespace (str): identifier for the method of interest

    Returns:
        module (ast.Module): the original module but with everything filtered
        away except the method name but with the name `namespace` and promoted
        to the global (i.e. top) level

    """
    module_name, class_name, method_name = namespace.split('.')
    classdefs = [stmt for stmt in module.body if isinstance(stmt, ast.ClassDef)]
    classdef, = [classdef for classdef in classdefs if classdef.name == class_name]
    methods = [stmt for stmt in classdef.body if isinstance(stmt, ast.FunctionDef)]
    for method in methods:
        if method.name == method_name:
            method.name = f'{module_name}.{class_name}.{method_name}'
            module.body = [method]
            return module 
開發者ID:ebanner,項目名稱:pynt,代碼行數:27,代碼來源:syntax.py

示例12: visit_ClassDef

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def visit_ClassDef(self, classdef):
        """Check the line number of each of the methods

        >>> self = DefunFinder(func_name='bar', lineno=4)
        >>> code = '''
        ...
        ... class Foo:
        ...     def bar():
        ...         \"\"\"function\"\"\"
        ...         pass
        ...     def biz():
        ...         \"\"\"function\"\"\"
        ...         pass
        ...
        ... '''
        >>>
        >>> tree = ast.parse(code)
        >>> classdef = tree.body[0]

        """
        methods = [stmt for stmt in classdef.body if isinstance(stmt, ast.FunctionDef)]
        for method in methods:
            if method.name == self.func_name and method.lineno == self.lineno:
                raise Exception(f'{classdef.name}.{method.name}')
        return classdef 
開發者ID:ebanner,項目名稱:pynt,代碼行數:27,代碼來源:node_transformers.py

示例13: _computeInitMethodAstOrNone

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def _computeInitMethodAstOrNone(pyClassObject):
    pyAst = pyAstFor(pyClassObject)

    assert len(pyAst.body) == 1

    classDef = pyAst.body[0]

    assert isinstance(classDef, ast.ClassDef)

    tr = None

    # recall ClassDef = (identifier name, expr* bases, stmt* body, expr* decorator_list)
    # we're taking the *last* __init__ here
    for stmt in classDef.body:
        if isinstance(stmt, ast.FunctionDef) and stmt.name == "__init__":
            tr = stmt

    return tr 
開發者ID:ufora,項目名稱:ufora,代碼行數:20,代碼來源:PyAstUtil.py

示例14: _fine_property_definition

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def _fine_property_definition(self, property_name):
        """Find the lines in the source code that contain this property's name and definition.

        This function can find both attribute assignments as well as methods/functions.

        Args:
            property_name (str): the name of the property to look up in the template definition

        Returns:
            tuple: line numbers for the start and end of the attribute definition
        """
        for node in ast.walk(ast.parse(self._source)):
            if isinstance(node, ast.Assign) and node.targets[0].id == property_name:
                return node.targets[0].lineno - 1, self._get_node_line_end(node)
            elif isinstance(node, ast.FunctionDef) and node.name == property_name:
                return node.lineno - 1, self._get_node_line_end(node)
        raise ValueError('The requested node could not be found.') 
開發者ID:robbert-harms,項目名稱:MDT,代碼行數:19,代碼來源:utils.py

示例15: get_comments_str

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import FunctionDef [as 別名]
def get_comments_str(file_name):
    with open(file_name) as fd:
        file_contents = fd.read()
    module = ast.parse(file_contents)

    function_definitions = [node for node in module.body if isinstance(node, ast.FunctionDef)]

    doc = get_func_comments(function_definitions)

    class_definitions = [node for node in module.body if isinstance(node, ast.ClassDef)]
    for class_def in class_definitions:
        temp_str = to_md(parse_func_string(ast.get_docstring(class_def)))

        # excludes private methods (start with '_')
        method_definitions = [
            node
            for node in class_def.body
            if isinstance(node, ast.FunctionDef) and (node.name[0] != '_' or node.name[:2] == '__')
        ]

        temp_str += get_func_comments(method_definitions)
        doc += '## class ' + class_def.name + '\n' + temp_str
    return doc 
開發者ID:idealo,項目名稱:image-quality-assessment,代碼行數:25,代碼來源:autogen.py


注:本文中的ast.FunctionDef方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。