mkinit.top_level_ast module

class mkinit.top_level_ast.TopLevelVisitor[source]

Bases: NodeVisitor

Parses top-level attribute names

References

# For other visit_<classname> values see http://greentreesnakes.readthedocs.io/en/latest/nodes.html

CommandLine

python ~/code/mkinit/mkinit/top_level_ast.py TopLevelVisitor:1

Example

>>> from xdoctest import utils
>>> source = utils.codeblock(
...    '''
...    def foo():
...        def subfunc():
...            pass
...    def bar():
...        pass
...    class Spam(object):
...        def eggs(self):
...            pass
...        @staticmethod
...        def hams():
...            pass
...    ''')
>>> self = TopLevelVisitor.parse(source)
>>> print('attrnames = {!r}'.format(sorted(self.attrnames)))
attrnames = ['Spam', 'bar', 'foo']

Example

>>> # xdoctest: +REQUIRES(PY3)
>>> from mkinit.top_level_ast import *  # NOQA
>>> from xdoctest import utils
>>> source = utils.codeblock(
...    '''
...    async def asyncfoo():
...        var = 1
...    def bar():
...        pass
...    class Spam(object):
...        def eggs(self):
...            pass
...        @staticmethod
...        def hams():
...            pass
...    ''')
>>> self = TopLevelVisitor.parse(source)
>>> print('attrnames = {!r}'.format(sorted(self.attrnames)))
attrnames = ['Spam', 'asyncfoo', 'bar']

Example

>>> from xdoctest import utils
>>> source = utils.codeblock(
...    '''
...    a = True
...    if a:
...        b = True
...        c = True
...    else:
...        b = False
...    d = True
...    del d
...    ''')
>>> self = TopLevelVisitor.parse(source)
>>> print('attrnames = {!r}'.format(sorted(self.attrnames)))
attrnames = ['a', 'b']

Example

>>> from xdoctest import utils
>>> source = utils.codeblock(
...    '''
...    try:
...        d = True
...        e = True
...    except ImportError:
...        raise
...    except Exception:
...        d = False
...        f = False
...    else:
...        f = True
...    ''')
>>> self = TopLevelVisitor.parse(source)
>>> print('attrnames = {!r}'.format(sorted(self.attrnames)))
attrnames = ['d', 'f']
_register(name)[source]
_unregister(name)[source]
classmethod parse(source)[source]
visit_FunctionDef(node)[source]
visit_AsyncFunctionDef(node)[source]
visit_ClassDef(node)[source]
visit_Assign(node)[source]
visit_If(node)[source]

Note

elif clauses don’t have a special representation in the AST, but rather appear as extra If nodes within the orelse section of the previous one.

visit_Try(node)[source]

We only care about checking if (a) a variable is defined in the main body, and (b) that the variable is defined in all except blacks that don’t immediately re-raise.

visit_TryExcept(node)

We only care about checking if (a) a variable is defined in the main body, and (b) that the variable is defined in all except blacks that don’t immediately re-raise.

visit_Delete(node)[source]