Listing top-level functions in Python
I had an interesting conversation today that brought up an unusual use case for parsing out (top-level) functions in a python file.
My first draft produced code that could have a number of problems... the biggest being security. As it imported the python file, code could be executed. Another likely problem revolves around long running processes and how python handles imports. Even if the import is handled in a function's namespace, the setup functions, etc will only be executed once. Even trying to catch for this with re-import, the way the internal dictionaries are updated would likely result in unexpected behavior.
This may not be the ideal solution, but it is fairly safe (no code execution) and still uses the CPython interpreter/compiler rather than trying to parse with regex, etc. This is a quick bit of code and does not include proper error handling.
#!/bin/env python3
# NOTE: requires python >= 3.2
import parser
def moduleFunctions(fileName):
d = {}
with open(fileName, 'r') as myfile:
code_str = myfile.read()
code_obj = parser.suite(code_str).compile()
for obj in code_obj.co_consts:
if isinstance(obj, type(code_obj)):
d[obj.co_name] = obj.co_varnames[slice(obj.co_argcount)]
return d