1

I have an auto-generated Python code snippet which I'd like to exec() from within a class instance.

A simplified snippet looks like this:

prog = """
def func1():
  func2()

def func2():
  pass

func1()
"""

class test():
    def run(self):
        exec(prog)

test().run()   # results in NameError: name 'func2' is not defined
exec(prog)     # works

While func1() can be called in both cases, func2 isn't found when exec()'ing from within the class. If I run the exec(prog) first, then even the test().run() succeeds. It seems that the previous exec call left func2 at some place in the namespace where it can later be found when called from within the class.

Is there a simple and clean way to call such a code snippet containing several functions from within a class?

3
  • Interesting. Your code works as written in Python 2 but I get your error on Python 3. Can you confirm you are on Python 3? Commented Dec 21, 2016 at 8:17
  • Ah yes. Read this: stackoverflow.com/a/15087355/5014455 Commented Dec 21, 2016 at 8:19
  • Yes, i am using Python3. Commented Dec 21, 2016 at 8:38

3 Answers 3

2

You can use exec(prog, globals()) to execute the code in the global namespace.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot. This does exactly what i was hoping for.
You don' t happen to know why func1() can be called in my initial approach and why only func2 was missing? Why is only func2 affected by this limitation?
func1 and func2 exist in the namespace (ie dictionary) where the execution holds. In your code it is the local namespace of function run(). As func1() is called in the same namespace, it works.
1

Not that I endorse using exec... But declare the function name global:

prog = """
global func1, func2
def func1():
  func2()

def func2():
  pass

func1()
"""

1 Comment

Looks good. But i'd have to parse the incoming code, search for functions and add the global statement automatically. The exec(prog, globals()) approach runs the unmodified code.
1

It is redundant to use exec for that.

class is itself an executable statement.

2 Comments

But a class does not parse and execute text strings. So, exec is still needed.
Yes. This is just a simplified test. In reality the code to be executed comes from somewhere else.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.