Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python eval()

#1
Python eval()

<div><p>This tutorial shows you how to use <a href="https://blog.finxter.com/python-built-in-functions/" target="_blank" rel="noreferrer noopener" title="Python Built-In Functions">Python’s built-in</a> <code>eval()</code> function. </p>
<p><strong>Why Using It? </strong>The main application of <code>eval()</code> 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!</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python eval() -- How to Dynamically Evaluate a Code Expression in Python" width="1400" height="788" src="https://www.youtube.com/embed/2SV60ENwXVw?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<p><strong>How does it work? TLDR;</strong></p>
<p class="has-pale-cyan-blue-background-color has-background">Python <code>eval(s)</code> parses the string argument <code>s</code> 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 <code>eval(input())</code>, a user could type <code>os.system('rm -R *')</code> to delete all files in your home directory.</p>
<h2>Usage Examples</h2>
<p>Learn by example! Here are some examples of how to use the <code>eval()</code> <a href="https://blog.finxter.com/python-built-in-functions/" target="_blank" rel="noreferrer noopener" title="Python Built-In Functions">built-in function</a>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> 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'</pre>
<p>You can run any Python code that has a return value within the <code>eval()</code> code. You can even create your own function and run it within <code>eval()</code>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> def f(): return 42 >>> eval('f()')
42</pre>
<p>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. </p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2020/12/eval-1-1024x576.jpg" alt="Python eval() - Visual Explanation" class="wp-image-19255" srcset="https://blog.finxter.com/wp-content/uploads/2020/12/eval-1-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...150x84.jpg 150w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<h2>Syntax eval()</h2>
<p>You can use the <code>eval()</code> method with three different argument lists. </p>
<pre class="wp-block-preformatted"><strong>Syntax: </strong>
<code><strong>eval(string)</strong></code>
<code><strong><code><strong>eval</strong></code>(<code><strong>string</strong></code>, globals)</strong></code>
<code><strong><code><strong>eval</strong></code>(<code><strong>string</strong></code>, globals, locals)</strong> </code></pre>
<figure class="wp-block-table is-style-stripes">
<table>
<tbody>
<tr>
<td><strong>Arguments</strong></td>
<td><code><code>string</code></code></td>
<td>A string to be evaluated.</td>
</tr>
<tr>
<td></td>
<td><code>globals</code></td>
<td>Optional, default <code>None</code>. A dictionary in which you can define variables that should be globally accessible by the executed <code>object</code> (local namespace). </td>
</tr>
<tr>
<td></td>
<td><code>locals</code></td>
<td>Optional, default <code>None</code>. A dictionary in which you can define variables that should be locally accessible by the executed <code>object</code> (global namespace).</td>
</tr>
<tr>
<td><strong>Return Value</strong></td>
<td><code>object</code></td>
<td>Returns the result of parsing the <code>string</code> argument and running it as a Python expression.</td>
</tr>
</tbody>
</table>
</figure>
<h2>Python eval() Return Value</h2>
<p>The return value of <code>eval()</code> is a Python object that is the result of parsing the <code>string</code> 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! </p>
<hr class="wp-block-separator"/>
<p><strong>But before we move on, I’m excited to present you my brand-new Python book <a rel="noreferrer noopener" href="https://amzn.to/2WAYeJE" target="_blank" title="https://amzn.to/2WAYeJE">Python One-Liners</a></strong> (Amazon Link).</p>
<p>If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a <strong>single line of Python code.</strong> But it’s also an <strong>introduction to computer science</strong>, data science, machine learning, and algorithms. <strong><em>The universe in a single line of Python!</em></strong></p>
<div class="wp-block-image">
<figure class="aligncenter"><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="215" height="283" src="https://blog.finxter.com/wp-content/uploads/2020/02/image-1.png" alt="" class="wp-image-5969"/></a></figure>
</div>
<p>The book is released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco). </p>
<p>Link: <a href="https://nostarch.com/pythononeliners" target="_blank" rel="noreferrer noopener">https://nostarch.com/pythononeliners</a></p>
<h2>[Danger Zone] Python eval(input()) User Input</h2>
<p>You can use the <code>eval()</code> function to run code that is typed in dynamically by the user:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def dangerous_function(): # Do nasty stuff like removing files # or creating trojan horses print('You were hacked!') return 42 eval(input())
</pre>
<p>This is how the user may interact with your code at runtime:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">dangerous_function()
You were hacked! 42</pre>
<p>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 <code>os.system('rm -rf *')</code> to remove all files and folders.</p>
<h2>Interactive Jupyter Notebook eval()</h2>
<p><em><strong>Exercise</strong>: Run the following interactive code and try to run the dangerous function in the interactive Jupyter notebook!</em></p>
<figure class="wp-block-image size-large"><a href="https://colab.research.google.com/drive/1RZR2qVzAYRKof_GaDbTVCHGW9m0AHL6E?usp=sharing" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="640" height="320" src="https://blog.finxter.com/wp-content/uploads/2020/12/image-80.png" alt="" class="wp-image-19226" srcset="https://blog.finxter.com/wp-content/uploads/2020/12/image-80.png 640w, https://blog.finxter.com/wp-content/uplo...00x150.png 300w, https://blog.finxter.com/wp-content/uplo...150x75.png 150w" sizes="(max-width: 640px) 100vw, 640px" /></a></figure>
<hr class="wp-block-separator"/>
<h2>Python exec() vs eval()</h2>
<p>Python’s <code>exec()</code> function takes a Python program, as a string or executable object, and runs it. The <code>eval()</code> function evaluates an expression and returns the result of this expression. There are two main differences:</p>
<ul>
<li><code>exec()</code> can execute all Python source code, whereas <code>eval()</code> can only evaluate expressions. </li>
<li><code>exec()</code> always returns <code>None</code>, whereas <code>eval()</code> returns the result of the evaluated expression.</li>
<li><code>exec()</code> can import modules, whereas <code>eval()</code> cannot. </li>
</ul>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">exec('x=2;y=2;z=x*y;print(z)')
# 4 print(eval('2*2'))
# 4
</pre>
<h2>Python eval() import</h2>
<p>Can you import a Python library within the <code>eval()</code> function? No, you can’t! The <code>import</code> statement is a statement, not an expression. But <code>eval()</code> can only execute expressions. A simple workaround is to create a function with side effects that imports the module within the function body:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def f(): import random return random.randint(0, 9) print(eval('f()'))
# 4</pre>
<p>Per default, the <code>eval()</code> function has access to all names in the <code>dir()</code> namespace, so you can also import the library globally and use it within the <code>eval()</code> function:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import random
print(eval('random.randint(0, 9)'))</pre>
<h2>How to Restrict the Use of Built-in Functions Within eval()</h2>
<p>If you don’t want to allow users to access built-in functions, you can restrict this by providing the <code>globals</code> argument as follows: </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">eval(expression, {'__builtins__': None})</pre>
<p>For example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> eval('sum([1, 2, 3])')
6
>>> eval('sum([1, 2, 3])', {'__builtins__': None})
Traceback (most recent call last): File "&lt;pyshell#13>", line 1, in &lt;module> eval('sum([1, 2, 3])', {'__builtins__': None}) File "&lt;string>", line 1, in &lt;module>
TypeError: 'NoneType' object is not subscriptable</pre>
<p>After restricting the built-in functions in the second call, Python raises an error <code>NoneType object is not subscriptable</code>. This reduces the security risks of your application.</p>
<h2>Summary</h2>
<p>Python <code>eval(s)</code> parses the string argument <code>s</code> into a Python expression, runs it, and returns the result of the expression. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">>>> eval('2+2')
4</pre>
<p>This 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>, a user could type <code>import os; os.system('rm -R *')</code> to delete all files in your home directory.</p>
<hr class="wp-block-separator"/>
<p>I hope you enjoyed the article! To improve your Python education, you may want to join the popular free <a href="https://blog.finxter.com/email-academy/" target="_blank" rel="noreferrer noopener" title="Email Academy">Finxter Email Academy</a>:</p>
<p>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!</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>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?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>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.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</p>
</p>
<p>The post <a href="https://blog.finxter.com/python-eval/" target="_blank" rel="noopener noreferrer">Python eval()</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/12/22/python-eval/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016