Loading functions from a file during run-time

Bryant Huang 735115 at gmail.com
Thu Feb 10 22:13:18 EST 2005


Hello!

I would like to read in files, during run-time, which contain plain
Python function definitions, and then call those functions by their
string name. In other words, I'd like to read in arbitrary files with
function definitions, using a typical 'open()' call, but then have
those functions available for use.

The 'import' keyword is not appropriate, AFAIK, because I want to be
able to open any file, not one that I know ahead of time (and thus can
import at design-time).

I already have some code that I cobbled together from many newsgroup
posts, but I wonder if there's a cleaner/simpler way to do it.

The following is a toy example of what I'm doing so far. I have a file
called 'bar.txt' that contains two function definitions. I have a main
driver program called 'foo.py' which reads in 'bar.txt' (but should be
able to read any file it hasn't seen before), then calls the two
functions specified in 'bar.txt'.

===== [bar.txt] =====

def negate(x):
	return -x

def square(x):
	return x*x


===== [foo.py] =====

# open functions file
foo_file = open("bar.txt")
foo_lines = foo_file.readlines()
foo_file.close()
foo_str = "".join(foo_lines)

# compile code
foo_code = compile(foo_str, "<string>", "exec")
foo_ns = {}
exec(foo_code) in foo_ns

# use functions
k = 5
print foo_ns["negate"](k)  // outputs -5
print foo_ns["square"](k)  // outputs 25


I'm not sure exactly what happens below the surface, but I'm guessing
the 'compile()' and 'exec()' commands load in 'negate()' and 'square()'
as functions in the global scope of 'foo.py'. I find that when I run
'compile()' and 'exec()' from within a function, say 'f()', the
functions I read in from 'bar.txt' are no longer accessible since they
are in global scope, and not in the scope of 'f()'.

Any pointers would be very welcome.

Thanks!
Bryant




More information about the Python-list mailing list