Python ast.ClassDef() Examples

The following are 30 code examples of ast.ClassDef(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ast , or try the search function .
Example #1
Source File: checkpatch.py    From s3ql with GNU General Public License v3.0 6 votes vote down vote up
def _iter_definitions(node):
    if isinstance(node, ast.Assign):
        for node in node.targets:
            while isinstance(node, ast.Attribute):
                node = node.value
            assert isinstance(node, ast.Name)
            yield node.id
    elif isinstance(node, (ast.FunctionDef, ast.ClassDef)):
        yield node.name
    elif isinstance(node, ast.If):
        for snode in node.body:
            yield from _iter_definitions(snode)
        for snode in node.orelse:
            yield from _iter_definitions(snode)
    elif isinstance(node, ast.Try):
        for snode in (node.body, node.finalbody, node.orelse):
            for ssnode in snode:
                yield from _iter_definitions(ssnode)
        for snode in node.handlers:
            assert isinstance(snode, ast.ExceptHandler)
            for ssnode in snode.body:
                yield from _iter_definitions(ssnode) 
Example #2
Source File: _ast_to_ir2.py    From tmppy with Apache License 2.0 6 votes vote down vote up
def add_custom_type_symbol(self,
                               custom_type: ir2.CustomType,
                               definition_ast_node: Union[ast.ClassDef, ast.ImportFrom, None],
                               source_module: Optional[str] = None):
        self.add_symbol(name=custom_type.name,
                        expr_type=ir2.FunctionType(argtypes=tuple(arg.expr_type
                                                                  for arg in custom_type.arg_types),
                                                   argnames=tuple(arg.name
                                                                  for arg in custom_type.arg_types),
                                                   returns=custom_type),
                        definition_ast_node=definition_ast_node,
                        is_only_partially_defined=False,
                        is_function_that_may_throw=False)
        self.custom_types_symbol_table.add_symbol(name=custom_type.name,
                                                  expr_type=custom_type,
                                                  definition_ast_node=definition_ast_node,
                                                  is_only_partially_defined=False,
                                                  is_function_that_may_throw=False,
                                                  source_module=source_module) 
Example #3
Source File: symbol_analyzer.py    From YAPyPy with MIT License 6 votes vote down vote up
def _visit_cls(self: 'ASTTagger', node: ast.ClassDef):
    bases = visit_suite(self.visit, node.bases)
    keywords = visit_suite(self.visit, node.keywords)
    decorator_list = visit_suite(self.visit, node.decorator_list)

    self.symtable.entered.add(node.name)

    new = self.symtable.enter_new()

    new.entered.add('__module__')
    new.entered.add('__qualname__')  # pep-3155 nested name.

    new_tagger = ASTTagger(new)
    new.cts.add(ContextType.ClassDef)
    body = visit_suite(new_tagger.visit, node.body)

    node.bases = bases
    node.keywords = keywords
    node.decorator_list = decorator_list
    node.body = body

    return Tag(node, new) 
Example #4
Source File: checker.py    From linter-pylama with MIT License 6 votes vote down vote up
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) 
Example #5
Source File: syntax.py    From pynt with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #6
Source File: PyAstUtil.py    From ufora with Apache License 2.0 6 votes vote down vote up
def classDefAtLineNumber(sourceAst, lineNumber):
    visitor = _AtLineNumberVisitor(lineNumber)
    visitor.visit(sourceAst)

    subnodesAtLineNumber = visitor.classDefSubnodesAtLineNumber

    if len(subnodesAtLineNumber) == 0:
        raise Exceptions.CantGetSourceTextError(
            "Can't find a ClassDef at line %s." % lineNumber
            )
    if len(subnodesAtLineNumber) > 1:
        raise Exceptions.CantGetSourceTextError(
            "Can't find a unique ClassDef at line %s." % lineNumber
            )

    return subnodesAtLineNumber[0] 
Example #7
Source File: PyAstUtil.py    From ufora with Apache License 2.0 6 votes vote down vote up
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 
Example #8
Source File: autogen.py    From image-quality-assessment with Apache License 2.0 6 votes vote down vote up
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 
Example #9
Source File: utils.py    From ansible-testing with GNU General Public License v3.0 6 votes vote down vote up
def find_globals(g, tree):
    """Uses AST to find globals in an ast tree"""
    for child in tree:
        if hasattr(child, 'body') and isinstance(child.body, list):
            find_globals(g, child.body)
        elif isinstance(child, (ast.FunctionDef, ast.ClassDef)):
            g.add(child.name)
            continue
        elif isinstance(child, ast.Assign):
            try:
                g.add(child.targets[0].id)
            except (IndexError, AttributeError):
                pass
        elif isinstance(child, ast.Import):
            g.add(child.names[0].name)
        elif isinstance(child, ast.ImportFrom):
            for name in child.names:
                g_name = name.asname or name.name
                if g_name == '*':
                    continue
                g.add(g_name) 
Example #10
Source File: test_ast.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_classdef(self):
        def cls(bases=None, keywords=None, body=None, decorator_list=None):
            if bases is None:
                bases = []
            if keywords is None:
                keywords = []
            if body is None:
                body = [ast.Pass()]
            if decorator_list is None:
                decorator_list = []
            return ast.ClassDef("myclass", bases, keywords,
                                body, decorator_list)
        self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
                  "must have Load context")
        self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
                  "must have Load context")
        self.stmt(cls(body=[]), "empty body on ClassDef")
        self.stmt(cls(body=[None]), "None disallowed")
        self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
                  "must have Load context") 
Example #11
Source File: test_ast.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_classdef(self):
        def cls(bases=None, keywords=None, starargs=None, kwargs=None,
                body=None, decorator_list=None):
            if bases is None:
                bases = []
            if keywords is None:
                keywords = []
            if body is None:
                body = [ast.Pass()]
            if decorator_list is None:
                decorator_list = []
            return ast.ClassDef("myclass", bases, keywords, starargs,
                                kwargs, body, decorator_list)
        self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
                  "must have Load context")
        self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
                  "must have Load context")
        self.stmt(cls(starargs=ast.Name("x", ast.Store())),
                  "must have Load context")
        self.stmt(cls(kwargs=ast.Name("x", ast.Store())),
                  "must have Load context")
        self.stmt(cls(body=[]), "empty body on ClassDef")
        self.stmt(cls(body=[None]), "None disallowed")
        self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
                  "must have Load context") 
Example #12
Source File: ast.py    From kale with Apache License 2.0 6 votes vote down vote up
def parse_functions(code):
    """Parse all the global functions present in the input code.

    Parse all the ast nodes ast.FunctionDef that are global functions in the
    source code. These also include function that are defined inside other
    Python statements, like `try`. ast.ClassDef nodes are skipped from the
    parsing so that class functions are ignored.

    Args:
        code (str): Multiline string representing Python code

    Returns (dict): A dictionary [fn_name] -> function_source
    """
    fns = dict()
    tree = ast.parse(code)
    for block in tree.body:
        for node in walk(block,
                         stop_at=(ast.FunctionDef,),
                         ignore=(ast.ClassDef,)):
            if isinstance(node, (ast.FunctionDef,)):
                fn_name = node.name
                fns[fn_name] = astor.to_source(node)
    return fns 
Example #13
Source File: test_ast.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 6 votes vote down vote up
def test_classdef(self):
        def cls(bases=None, keywords=None, body=None, decorator_list=None):
            if bases is None:
                bases = []
            if keywords is None:
                keywords = []
            if body is None:
                body = [ast.Pass()]
            if decorator_list is None:
                decorator_list = []
            return ast.ClassDef("myclass", bases, keywords,
                                body, decorator_list)
        self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
                  "must have Load context")
        self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
                  "must have Load context")
        self.stmt(cls(body=[]), "empty body on ClassDef")
        self.stmt(cls(body=[None]), "None disallowed")
        self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
                  "must have Load context") 
Example #14
Source File: __init__.py    From NodeGraphQt with MIT License 6 votes vote down vote up
def detectNodesFromText(filepath):
    """returns Node names from a python script"""
    froms = []

    with open(filepath, "r") as source:
        tree = ast.parse(source.read())
    
    for node in tree.body:
        if isinstance(node, ast.ClassDef):
            for base in node.bases:
                if base.id in VALID_NODE_TYPE:
                    for indef in node.body:
                        if isinstance(indef, ast.Assign):
                            for target in indef.targets:
                                if target.id == '__identifier__':
                                    froms.append(node.name)
    return froms 
Example #15
Source File: autogen.py    From imageatm with Apache License 2.0 6 votes vote down vote up
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 
Example #16
Source File: tracer.py    From executing with MIT License 6 votes vote down vote up
def _main_frame(self, node):
        # type: (ast.AST) -> Optional[FrameType]
        frame = sys._getframe(2)
        result = self.secondary_to_main_frames.get(frame)
        if result:
            return result

        original_frame = frame

        while frame.f_code.co_name in ('<listcomp>', '<dictcomp>', '<setcomp>'):
            frame = frame.f_back

        for node in ancestors(node):
            if isinstance(node, (ast.FunctionDef, ast.Lambda)):
                break

            if isinstance(node, ast.ClassDef):
                frame = frame.f_back

        if frame.f_code.co_name in ('<lambda>', '<genexpr>'):
            return None

        self.secondary_to_main_frames[original_frame] = frame
        self.main_to_secondary_frames[frame].append(original_frame)
        return frame 
Example #17
Source File: checker.py    From blackmamba with MIT License 6 votes vote down vote up
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) 
Example #18
Source File: outline_quickly.py    From blackmamba with MIT License 6 votes vote down vote up
def _generate_nodes(parent, level=0, breadcrumb=''):
        nodes = []

        for child in parent.body:
            if isinstance(child, ast.ClassDef):
                style = OutlineNodeItem.Style.cls
            elif isinstance(child, ast.FunctionDef) or isinstance(child, ast.AsyncFunctionDef):
                style = OutlineNodeItem.Style.fn
            else:
                style = None

            if style:
                node = OutlineNodeItem(style, child.name, child.lineno, child.col_offset, level, breadcrumb)
                nodes.append(node)
                if breadcrumb:
                    bc = '{} • {}'.format(breadcrumb, child.name)
                else:
                    bc = child.name
                child_nodes = OutlineDataSource._generate_nodes(child, level + 1, bc)
                if child_nodes:
                    nodes.extend(child_nodes)

        return nodes 
Example #19
Source File: checker.py    From pyflakes with MIT License 6 votes vote down vote up
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, '_pyflakes_parent'):
            n, n_child = n._pyflakes_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 and not PY38_PLUS:
                    self.report(messages.ContinueInFinally, node)
                    return
        if isinstance(node, ast.Continue):
            self.report(messages.ContinueOutsideLoop, node)
        else:  # ast.Break
            self.report(messages.BreakOutsideLoop, node) 
Example #20
Source File: ast.py    From kale with Apache License 2.0 6 votes vote down vote up
def get_function_and_class_names(code):
    """Get all function and class names of the code block.

    Inspects the code walking through its AST and returns all
    the names of nodes matching ast.FunctionDef or ast.ClassDef.

    Args:
        code: Multiline string representing Python code

    Returns: List of string names
    """
    names = set()
    tree = ast.parse(code)
    for block in tree.body:
        for node in walk(block):
            if isinstance(node, (ast.FunctionDef, ast.ClassDef,)):
                names.add(node.name)
    return names 
Example #21
Source File: visitor.py    From docstr_coverage with MIT License 5 votes vote down vote up
def visit_ClassDef(self, node: ClassDef):
        """Collect information regarding class declaration nodes"""
        self._visit_helper(node) 
Example #22
Source File: bugbear.py    From flake8-bugbear with MIT License 5 votes vote down vote up
def visit_Assign(self, node):
        if isinstance(self.node_stack[-2], ast.ClassDef):
            # note: by hasattr below we're ignoring starred arguments, slices
            # and tuples for simplicity.
            assign_targets = {t.id for t in node.targets if hasattr(t, "id")}
            if "__metaclass__" in assign_targets:
                self.errors.append(B303(node.lineno, node.col_offset))
        elif len(node.targets) == 1:
            t = node.targets[0]
            if isinstance(t, ast.Attribute) and isinstance(t.value, ast.Name):
                if (t.value.id, t.attr) == ("os", "environ"):
                    self.errors.append(B003(node.lineno, node.col_offset))
        self.generic_visit(node) 
Example #23
Source File: custom_rules.py    From warriorframework with Apache License 2.0 5 votes vote down vote up
def class_check(node, kw=False):
    '''
    Class specific check
        Action - check private method, move to utils
        check docstring
        scan for class - recursive class check
        scan for function - function check
    '''
    status = True

    for child in ast.iter_child_nodes(node):
        if isinstance(child, ast.FunctionDef):
            if kw and child.name.startswith("_") and child.name != "__init__":
                print node.name, child.name, "should move to utils"
                status = False
            tmp_status = func_check(child, kw)
            status &= tmp_status
        elif isinstance(child, ast.ClassDef):
            tmp_status = class_check(child, kw)
            status &= tmp_status

    if ast.get_docstring(node) is None:
        # check for docstring
        print node.name, "doesn't contain any docstring"
        status = False
    return status 
Example #24
Source File: backend.py    From thonny with MIT License 5 votes vote down vote up
def parse_api_information(file_path):
    import tokenize

    with tokenize.open(file_path) as fp:
        source = fp.read()

    tree = ast.parse(source)

    defs = {}

    # TODO: read also docstrings ?

    for toplevel_item in tree.body:
        if isinstance(toplevel_item, ast.ClassDef):
            class_name = toplevel_item.name
            member_names = []
            for item in toplevel_item.body:
                if isinstance(item, ast.FunctionDef):
                    member_names.append(item.name)
                elif isinstance(item, ast.Assign):
                    # TODO: check Python 3.4
                    "TODO: item.targets[0].id"

            defs[class_name] = member_names

    return defs 
Example #25
Source File: autodoc.py    From FRU with MIT License 5 votes vote down vote up
def top_level_classes(body):
    return (f for f in body if isinstance(f, ast.ClassDef)) 
Example #26
Source File: ast_helpers.py    From fiasko_bro with MIT License 5 votes vote down vote up
def is_class_attribute(assigned_item):
    if not hasattr(assigned_item, 'parent'):
        return False
    if not hasattr(assigned_item.parent, 'parent'):
        return False
    return isinstance(assigned_item.parent.parent, ast.ClassDef) 
Example #27
Source File: add_trailing_comma.py    From add-trailing-comma with MIT License 5 votes vote down vote up
def visit_ClassDef(self, node: ast.ClassDef) -> None:
        # starargs are allowed in py3 class definitions, py35+ allows trailing
        # commas.  py34 does not, but adding an option for this very obscure
        # case seems not worth it.
        has_starargs = False
        args = [*node.bases, *node.keywords]
        arg_offsets = {_to_offset(arg) for arg in args}

        if arg_offsets:
            key = _to_offset(node)
            self.classes[key] = Node(has_starargs, arg_offsets)

        self.generic_visit(node) 
Example #28
Source File: base_model_checker.py    From flake8-django with GNU General Public License v3.0 5 votes vote down vote up
def is_abstract_model(self, base):
        """
        Return True if AST node has a Meta class with abstract = True.
        """
        # look for "class Meta"
        for element in base.body:
            if isinstance(element, ast.ClassDef) and element.name == 'Meta':
                # look for "abstract = True"
                for inner_element in element.body:
                    if self._is_abstract_and_set_to_true(inner_element):
                        return True
        return False 
Example #29
Source File: model_content_order.py    From flake8-django with GNU General Public License v3.0 5 votes vote down vote up
def is_meta_declaration(node):
    return isinstance(node, ClassDef) and node.name == 'Meta' 
Example #30
Source File: ast_helpers.py    From fiasko_bro with MIT License 5 votes vote down vote up
def is_nonglobal_item(node, max_indentation_depth):
    current_item = node
    # prevents the user from making this loop excessively long
    for _ in range(max_indentation_depth):
        if (
                not hasattr(current_item, 'parent') or
                isinstance(current_item.parent, ast.Module)
        ):
            break
        if not isinstance(current_item.parent, (ast.ClassDef, ast.Assign, ast.If)):
            return True
        current_item = current_item.parent
    return False