12-22-2020, 11:50 PM
Python eval()
This tutorial shows you how to use Python’s built-in function.
Why Using It? The main application of is to take user input at runtime and run it as a Python expression. This way, you can create a calculator or allow users to perform custom computations on a computing cluster. However, this use also poses the biggest security risk: the user can run byzantine (=harmful) code on your server environment!
How does it work? TLDR;
Python parses the string argument into a Python expression, runs it, and returns the result of the expression. This poses a security risk because a user can use it to run code on your computer. For example, if you allow , a user could type to delete all files in your home directory.
Usage Examples
Learn by example! Here are some examples of how to use the built-in function:
You can run any Python code that has a return value within the code. You can even create your own function and run it within :
This gives you great flexibility in how you use the function to run any string expression you may encounter in Python and it allows you to create Python code programmatically and evaluate it at runtime.
![[Image: eval-1-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/12/eval-1-1024x576.jpg)
Syntax eval()
You can use the method with three different argument lists.
Arguments |
|
A string to be evaluated.
|
|
Optional, default. A dictionary in which you can define variables that should be globally accessible by the executed (local namespace).
|
|
Optional, default. A dictionary in which you can define variables that should be locally accessible by the executed (global namespace).
Return Value |
|
Returns the result of parsing the argument and running it as a Python expression.
Python eval() Return Value
The return value of is a Python object that is the result of parsing the argument and running it as a Python expression. The code can have side effects which means that it may change the state of your program or even your computer!
But before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
![[Image: image-1.png]](https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png)
The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Link: https://nostarch.com/pythononeliners
[Danger Zone] Python eval(input()) User Input
You can use the function to run code that is typed in dynamically by the user:
This is how the user may interact with your code at runtime:
You see that the dangerous_function() was executed which could contain all kinds of dangerous code. If you run this on your server, the user may attempt to remove all files on your server! For example, the user may use the command to remove all files and folders.
Interactive Jupyter Notebook eval()
Exercise: Run the following interactive code and try to run the dangerous function in the interactive Jupyter notebook!
![[Image: image-80.png]](https://blog.finxter.com/wp-content/uploads/2020/12/image-80.png)
Python 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:
Python eval() import
Can you import a Python library within the function? No, you can’t! The statement is a statement, not an expression. But can only execute expressions. A simple workaround is to create a function with side effects that imports the module within the function body:
Per default, the function has access to all names in the namespace, so you can also import the library globally and use it within the function:
How to Restrict the Use of Built-in Functions Within eval()
If you don’t want to allow users to access built-in functions, you can restrict this by providing the argument as follows:
For example:
After restricting the built-in functions in the second call, Python raises an error. This reduces the security risks of your application.
Summary
Python parses the string argument into a Python expression, runs it, and returns the result of the expression.
This poses a security risk because a user can use it to run code on your computer. For example, if you allow, a user could type to delete all files in your home directory.
I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:
Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become 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.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
The post Python eval() first appeared on Finxter.
This tutorial shows you how to use Python’s built-in
Code:
eval()Why Using It? The main application of
Code:
eval()How does it work? TLDR;
Python
Code:
eval(s)Code:
sCode:
eval(input())Code:
os.system('rm -R *')Usage Examples
Learn by example! Here are some examples of how to use the
Code:
eval()Code:
>>> eval('2+2')
4
>>> eval('[1, 2, 3]*3')
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> eval('[x for x in range(10)]')
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> eval('"Alice".replace("e", "")') 'Alic'You can run any Python code that has a return value within the
Code:
eval()Code:
eval()Code:
>>> def f(): return 42 >>> eval('f()')
42This gives you great flexibility in how you use the function to run any string expression you may encounter in Python and it allows you to create Python code programmatically and evaluate it at runtime.
![[Image: eval-1-1024x576.jpg]](https://blog.finxter.com/wp-content/uploads/2020/12/eval-1-1024x576.jpg)
Syntax eval()
You can use the
Code:
eval()Code:
Syntax:
eval(string)
eval(string, globals)
eval(string, globals, locals)Arguments |
Code:
stringA string to be evaluated.
|
Code:
globalsOptional, default
Code:
NoneCode:
object|
Code:
localsOptional, default
Code:
NoneCode:
objectReturn Value |
Code:
objectReturns the result of parsing the
Code:
stringPython eval() Return Value
The return value of
Code:
eval()Code:
stringBut before we move on, I’m excited to present you my brand-new Python book Python One-Liners (Amazon Link).
If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!
![[Image: image-1.png]](https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png)
The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).
Link: https://nostarch.com/pythononeliners
[Danger Zone] Python eval(input()) User Input
You can use the
Code:
eval()Code:
def dangerous_function(): # Do nasty stuff like removing files # or creating trojan horses print('You were hacked!') return 42 eval(input())This is how the user may interact with your code at runtime:
Code:
dangerous_function()
You were hacked! 42You see that the dangerous_function() was executed which could contain all kinds of dangerous code. If you run this on your server, the user may attempt to remove all files on your server! For example, the user may use the command
Code:
os.system('rm -rf *')Interactive Jupyter Notebook eval()
Exercise: Run the following interactive code and try to run the dangerous function in the interactive Jupyter notebook!
![[Image: image-80.png]](https://blog.finxter.com/wp-content/uploads/2020/12/image-80.png)
Python 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()
Code:
exec('x=2;y=2;z=x*y;print(z)')
# 4 print(eval('2*2'))
# 4Can you import a Python library within the
Code:
eval()Code:
importCode:
eval()Code:
def f(): import random return random.randint(0, 9) print(eval('f()'))
# 4Per default, the
Code:
eval()Code:
dir()Code:
eval()Code:
import random
print(eval('random.randint(0, 9)'))If you don’t want to allow users to access built-in functions, you can restrict this by providing the
Code:
globalsCode:
eval(expression, {'__builtins__': None})For example:
Code:
>>> eval('sum([1, 2, 3])')
6
>>> eval('sum([1, 2, 3])', {'__builtins__': None})
Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> eval('sum([1, 2, 3])', {'__builtins__': None}) File "<string>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptableAfter restricting the built-in functions in the second call, Python raises an error
Code:
NoneType object is not subscriptableSummary
Python
Code:
eval(s)Code:
sCode:
>>> eval('2+2')
4This poses a security risk because a user can use it to run code on your computer. For example, if you allow
Code:
eval(input())Code:
import os; os.system('rm -R *')I hope you enjoyed the article! To improve your Python education, you may want to join the popular free Finxter Email Academy:
Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become 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.
Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.
Join the free webinar now!
The post Python eval() first appeared on Finxter.

