Before offering my solution, I highly warn against do this unless you know for sure there is no malicious code in a.txt.
My solution uses the execfile
function to load the text file and return the first object (could be a variable or function):
def load_function(filename):
""" Assume that filename contains only 1 function """
global_var = dict()
execfile(filename, global_var)
del global_var['__builtins__']
return next(global_var.itervalues())
# Use it
myfunction = load_function('a.txt')
print myfunction()
Update
To be a little more careful, modify the return line like the following so that it skips variables (it cannot skip class declaration, however).
return next(f for f in global_var.itervalues() if callable(f))
Update 2
Thank you johnsharpe for pointing out that there is no execfile
in Python 3. Here is a modified solution which use exec
instead. This time, the function should be found in the "local" scope.
def load_function(filename):
""" Assume that filename contains only 1 function """
with open(filename) as f:
file_contents = f.read()
global_var = dict()
local_var = dict()
exec file_contents in global_var, local_var
return next(f for f in local_var.itervalues() if callable(f))
# Use it
myfunction = load_function('a.txt')
print myfunction()