Created
April 14, 2017 16:29
-
-
Save jbasko/569ed3e6f702db721a75f3ce74b91aa5 to your computer and use it in GitHub Desktop.
List names of functions declared in a Python module in the order of declaration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Gets list of functions in a module, preserve declaration order. | |
This cannot be done with inspect.getmembers() or dir() because they lose the order. | |
Have to construct AST with ast. | |
""" | |
import ast | |
import importlib | |
import os.path | |
class Parser(ast.NodeVisitor): | |
def __init__(self): | |
super(Parser, self).__init__() | |
self.functions = [] | |
def visit_FunctionDef(self, node): | |
self.functions.append(node.name) | |
class Inspector(object): | |
def __init__(self, mod_name): | |
self.mod_name = mod_name | |
self._mod_filename = None | |
self._ast = None | |
self._parser = None | |
@property | |
def mod_filename(self): | |
if self._mod_filename is None: | |
direct_path = self.mod_name.replace('.', '/') + '.py' | |
if os.path.exists(direct_path): | |
self._mod_filename = direct_path | |
else: | |
m = importlib.import_module(self.mod_name) | |
self._mod_filename = m.__file__ | |
return self._mod_filename | |
@property | |
def ast(self): | |
if self._ast is None: | |
with open(self.mod_filename) as f: | |
self._ast = ast.parse(f.read(), filename=self.mod_filename) | |
return self._ast | |
@property | |
def parser(self): | |
if self._parser is None: | |
self._parser = Parser() | |
self._parser.visit(self.ast) | |
return self._parser | |
def get_function_names(self): | |
return self.parser.functions | |
print(Inspector('idemseq.examples.context_provider').get_function_names()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment