Yes, you need to have the assignment within the exec
statement:
>>> def foo():
... return 5
...
>>> exec("a = foo()")
>>> a
5
This probably isn’t relevant for your case since its being used in controlled testing, but be careful with using exec
with user defined input.
More Related Contents:
- Why does my recursive function return None?
- How can I return two values from a function in Python?
- How to use a return statement in a for loop?
- Difference between returns and printing in python? [duplicate]
- How can I use `return` to get back multiple values from a for loop? Can I put them in a list?
- How do I pass variables across functions?
- Setting variables with exec inside a function
- How do I get a result (output) from a function? How can I use the result later?
- How can I use `return` to get back multiple values from a loop? Can I put them in a list?
- Is it possible to not return anything from a function in python?
- How does Python return multiple values from a function?
- Accessing returned values from a function, by another function
- Why doesn’t an import in an exec in a function work?
- How function is getting called without defining in python [closed]
- Check if input is empty
- How is returning the output of a function different from printing it?
- How do I execute a string containing Python code in Python?
- Behavior of exec function in Python 2 and Python 3
- Determine function name from within that function (without using traceback)
- How to plot multiple functions on the same figure, in Matplotlib?
- How to get local variables updated, when using the `exec` call?
- Best way to check function arguments? [closed]
- How are Python in-place operator functions different than the standard operator functions?
- How do Python functions handle the types of parameters that you pass in?
- Is it possible to run function in a subprocess without threading or writing a separate file/script.
- In Python, when should I use a function instead of a method?
- Tkinter PIL image not displaying inside of a function
- Where to use the return statement with a loop?
- Use a string to call function in Python [duplicate]
- Are functions objects in Python?