Reputation: 19628
I have a string format of the definition of a function, how can I turn it into a valid function.
I learned that I can use exec
command to make it work, but it feels like I am running a code with error.
msg = """
def myfunction(input):
output = input.upper()
return output"""
exec(msg)
print myfunction('hello World')
Clearly, the code above will run, because I can run and see the output: HELLO WORLD
, but when I write the code in the IDE (Eclipse/Pydev), it shows annoying error.
I am wondering is this(exec
) the right way to create a function if you have to create it based on a string?
or there are some more generic and better way to do this?
Thanks!
Upvotes: 1
Views: 67
Reputation: 4317
What about using the imp module, which should be more general and less error prone?
import imp
# create a new module
module = imp.new_module("myModule")
msg = """
def myfunction(input):
output = input.upper()
return output"""
# import code into myModule
exec msg in module.__dict__
print module.myfunction("test")
Upvotes: 3