05-21-2022, 08:01 AM
How to Assign the Result of eval() 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 eval()
Python parses the string argument into a Python expression, runs it, and returns the result of the expression.
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: Simple Assignment
The most straightforward way to store the result of an expression in a Python variable is to assign the whole return value to the variable. For example, the expression stores the result in the variable .
Here’s a minimal example:
This simple approach may not always work, for example, if you have a statement in the expression.
Read on to learn how to fix this issue next and learn something new!
Method 2: Redirect Standard Output
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.
Method 3: Use exec()
Using only Python’s function, you cannot define variables inside the expression to be evaluated. However, 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 termination of the expression!
Here’s how that works in a minimal example:
Variable is only defined in the string expression passed into , but you can use it in the code like it was part of the original source code.
Recap exec() vs eval()
Python’s function takes a Python program, as a string or executable object, and runs it. The function evaluates an expression and returns the result of this expression. There are two main differences:
You can learn more about the function here:
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:
eval()Code:
my_resultBefore I show you the solution, let’s quickly recap the
Code:
eval()Recap Python eval()
Python
Code:
eval(s)Code:
sRelated Tutorial: Python’s
Code:
eval()Without further ado, let’s learn how you can store the result of the
Code:
eval()Method 1: Simple Assignment
The most straightforward way to store the result of an
Code:
eval()Code:
my_result = eval('2+2')Code:
4Code:
my_resultHere’s a minimal example:
Code:
my_result = eval('2+2')
print(my_result)
# 4This simple approach may not always work, for example, if you have a
Code:
print()Read on to learn how to fix this issue next and learn something new!
Method 2: Redirect Standard Output
This method assumes you have a
Code:
print()Code:
eval()- Code:
eval('print(2+2)')
- Code:
eval('print([1, 2, 3, 4] + [5, 6])')
- Code:
eval('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 eval() expression here
eval(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())
# hello worldIf 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:
eval()Code:
print()- becomesCode:
eval('2+2')Code:eval('print(2+2)')
- becomesCode:
eval('2+2*0')Code:eval('print(2+2*0)')
- becomesCode:
eval('[1, 2, 3] + [4, 5]')Code:eval('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:
eval()Method 3: Use exec()
Using only Python’s
Code:
eval()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()Recap exec() vs eval()
Python’s
Code:
exec()Code:
eval()- can execute all Python source code, whereasCode:
exec()can only evaluate expressions.Code:eval()
- always returnsCode:
exec(), whereasCode:Nonereturns the result of the evaluated expression.Code:eval()
- can import modules, whereasCode:
exec()cannot.Code:eval()
You can learn more about the
Code:
exec()- Related Article: Python — A Hacker’s Guide to A Dangerous FunctionCode:
exec()
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!

