Import a module without executing it?

finite.automaton at gmail.com finite.automaton at gmail.com
Tue Dec 7 22:29:37 CET 2004


Functions and classes are created during the very execution you're
trying to skip so there's no precise way to do what you want.

That said, you can parse the code without executing it, and that will
give you some information about defined functions and classes.  It will
_not_ give you actual function objects; the only way to get those is to
execute the code.  It will also not catch anything created "on the
fly"*, e.g. "exec 'def func(x): pass'"


# example:

def defined_functions(code_text):
module_ast = parse(code_text)
return [statement for statement in
module_ast.node.nodes if
isinstance(statement, ast.Function)]

# read the module's source code
test_string = """
def foo(x):
pass
def bar(y):
pass
"""

# Which functions are defined in the test string?
function_asts = defined_functions(test_string)
print "Defined functions:", [f.name for f in function_asts]




* - Okay, everything in Python happens on-the-fly.  But you know what I
mean.

Footnote: Wow.  The new, "improved" google groups 2 beta has totally
annihilated my indentation.  Sorry about that.  Hopefully you can still
figure it out.




More information about the Python-list mailing list