05-22-2022, 07:24 AM
How to Assign the Result of exec() to a Python Variable?
5/5 – (1 vote)
Question: Say you have an expression you want to execute using the function. How to store the result of the expression in a Python variable ?
Before I show you the solution, let’s quickly recap the function:
Recap Python exec()
Python’s function executes the Python code you pass as a string or executable object argument.
This is called dynamic execution because, in contrast to normal static Python code, you can generate code and execute it at runtime.
This way, you can run programmatically-created Python code.
Related Tutorial: Python’s built-in function
Without further ado, let’s learn how you can store the result of the function in a Python variable:
Method 1: Define Variable in String Representation of Code
You can define a variable inside the function that will then be added to the global namespace. Thus, you can access the defined variable in your code after the termination of the expression!
Here’s how that works in a minimal example:
Variable is only defined in the string expression passed into . You can use it in the code like it was part of the original source code.
Method 2: How to Replace Value of a Variable in exec()
To replace a variable defined outside the function call, you can simply do so using an f-string and pass the new value as the right-hand side of the assignment operator within the string representation of the code to be executed.
Here’s a minimal example where we overwrite the with the new string by using the expression:
Method 3: How to Replace Global Variable in exec()?
If you use the previous approach to replace a global variable defined outside the expression that is called in a local context, the assignment operator will work on a local alias variable.
The global variable to be replaced will remain the same!
This can be seen in the following code example, where the global is not replaced with the new string because of the local scope of the function that creates its own namespace with its own that overshadows the global .
To overwrite a global variable within the function, use the keyword, followed by an empty space, the name of the global variable, a semicolon to close the statement, and the expression to overwrite the global variable like so:
Here’s the full example:
Related tutorial:
Method 4: Redirect Standard Output
Okay, let’s do something crazy, shall we?![[Image: 1f92f.png]](https://s.w.org/images/core/emoji/13.1.0/72x72/1f92f.png)
Let’s redirect the standard output and print directly to the variable!
![[Image: ExplodindoBoomExplosaoCabecaexplodindoGIF.gif]](https://blog.finxter.com/wp-content/uploads/2022/05/ExplodindoBoomExplosaoCabecaexplodindoGIF.gif)
This method assumes you have a statement within the expression passed into the function such as shown in the following three examples:
To get the output and store it in a variable, you need to temporarily redirect the standard output to the variable.
The following code shows you how to accomplish exactly this:
If you need some assistance understanding this whole idea of redirecting the standard output, have a look at our in-depth guide on the Finxter blog.
Related Article: 7 Easy Steps to Redirect Your Standard Output to a Variable (Python)
Note that this approach even works if you don’t have a statement in the original expression because you can always artificially add the statement around the original expression like so:
Even if it’s a bit clunky, after applying this short trick, you can redirect the standard output and store the result of any expression in a variable.
Related Article: How to Assign the Result of eval() to a Python Variable?
Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
5/5 – (1 vote)
Question: Say you have an expression you want to execute using the Code:
exec()Code:
my_resultBefore I show you the solution, let’s quickly recap the
Code:
exec()Recap Python exec()
Python’s
Code:
exec()This is called dynamic execution because, in contrast to normal static Python code, you can generate code and execute it at runtime.
This way, you can run programmatically-created Python code.
Related Tutorial: Python’s
Code:
exec()Without further ado, let’s learn how you can store the result of the
Code:
exec()Method 1: Define Variable in String Representation of Code
You can define a variable inside the
Code:
exec()Code:
exec()Here’s how that works in a minimal example:
Code:
exec('my_result = 40 + 2')
print(my_result)
# 42Variable
Code:
my_resultCode:
exec()Method 2: How to Replace Value of a Variable in exec()
To replace a variable defined outside the
Code:
exec()Here’s a minimal example where we overwrite the
Code:
old_variableCode:
'hello finxter'Code:
exec(f'old_variable = "{new_string}"')Code:
old_variable = 'hello world'
new_string = 'hello finxter' # Replace old_old variable with new string 'hello finxter'
exec(f'old_variable = "{new_string}"') print(old_variable)
# hello finxterIf you use the previous approach to replace a global variable defined outside the
Code:
exec()The global variable to be replaced will remain the same!
This can be seen in the following code example, where the global
Code:
old_variableCode:
'hello finxter'Code:
fCode:
old_variableCode:
old_variableCode:
old_variable = 'hello world'
new_string = 'hello finxter' def f(): # Replace old_old variable with new string 'hello finxter' exec(f'old_variable = "{new_string}"') f() print(old_variable)
# hello worldTo overwrite a global variable within the
Code:
exec()Code:
globalCode:
;Code:
exec(f'global old_variable; old_variable = "{new_string}"')Here’s the full example:
Code:
old_variable = 'hello world'
new_string = 'hello finxter' def f(): # Replace old_old variable with new string 'hello finxter' exec(f'global old_variable; old_variable = "{new_string}"') f() print(old_variable)
# hello finxterRelated tutorial:
Method 4: Redirect Standard Output
Okay, let’s do something crazy, shall we?
![[Image: 1f92f.png]](https://s.w.org/images/core/emoji/13.1.0/72x72/1f92f.png)
Let’s redirect the standard output and print directly to the variable!
![[Image: ExplodindoBoomExplosaoCabecaexplodindoGIF.gif]](https://blog.finxter.com/wp-content/uploads/2022/05/ExplodindoBoomExplosaoCabecaexplodindoGIF.gif)
This method assumes you have a
Code:
print()Code:
exec()- Code:
exec('print(2+2)')
- Code:
exec('print([1, 2, 3, 4] + [5, 6])')
- Code:
exec('print(2+2*0)')
To get the output and store it in a variable
Code:
my_resultThe following code shows you how to accomplish exactly this:
Code:
# Step 1: Import libraries StringIO and sys
from io import StringIO
import sys # Step 2: Keep stdout in temporary variable
tmp = sys.stdout # Step 3: Capture standard output using a StringIO object
my_result = StringIO() # Step 4: Assign Standard Output Stream to StringIO object
sys.stdout = my_result # Step 5: Print to the standard output
expression = 'print(2+2)' # any exec() expression here
exec(expression) # Step 6: Clean up by redirecting stdout to Python shell
sys.stdout = tmp # Step 7: Get and print the string from stdout
print('VARIABLE:', my_result.getvalue())
# VARIABLE: 4If you need some assistance understanding this whole idea of redirecting the standard output, have a look at our in-depth guide on the Finxter blog.
Related Article: 7 Easy Steps to Redirect Your Standard Output to a Variable (Python)Note that this approach even works if you don’t have a
Code:
print()Code:
exec()Code:
print()- becomesCode:
exec('2+2')Code:exec('print(2+2)')
- becomesCode:
exec('2+2*0')Code:exec('print(2+2*0)')
- becomesCode:
exec('[1, 2, 3] + [4, 5]')Code:exec('print([1, 2, 3] + [4, 5])')
Even if it’s a bit clunky, after applying this short trick, you can redirect the standard output and store the result of any
Code:
exec()
Related Article: How to Assign the Result of eval() to a Python Variable?Where to Go From Here?
Enough theory. Let’s get some practice!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!

