Import a module without executing it?

finite.automaton at finite.automaton at
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):
def bar(y):

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

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

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