B.Mr.W.
B.Mr.W.

Reputation: 19628

turn string into a valid function - exec or not

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.

enter image description here

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

Answers (2)

Roberto Reale
Roberto Reale

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

yorodm
yorodm

Reputation: 4461

There's nothing wrong. Your IDE just won't detect something that you are creating at runtime. If you're planing to use that in production you should also check this

Upvotes: 2

Related Questions