Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Assign the Result of eval() to a Python Variable?

#1
How to Assign the Result of eval() to a Python Variable?

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;367801&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> 5/5 – (1 vote) </div>
</div>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: Say you have an expression you want to execute using the <code><a href="https://blog.finxter.com/python-eval/" data-type="post" data-id="19204" target="_blank" rel="noreferrer noopener">eval()</a></code> function. How to store the result of the expression in a Python variable <code>my_result</code>?</p>
<p>Before I show you the solution, let’s quickly recap the <code>eval()</code> function:</p>
<h2>Recap Python eval()</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>
<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">
<iframe loading="lazy" title="Python eval() -- How to Dynamically Evaluate a Code Expression in Python" width="780" height="439" 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>
</figure>
<p><strong>Related Tutorial</strong>: <a href="https://blog.finxter.com/python-eval/" data-type="URL" data-id="https://blog.finxter.com/python-eval/" target="_blank" rel="noreferrer noopener">Python’s <code>eval()</code> built-in function</a></p>
<p>Without further ado, let’s learn how you can store the result of the <code>eval()</code> function in a Python variable:</p>
<h2>Method 1: Simple Assignment</h2>
<p class="has-global-color-8-background-color has-background">The most straightforward way to store the result of an <code>eval()</code> expression in a Python variable is to <a href="https://blog.finxter.com/python-in-place-assignment-operators/" data-type="post" data-id="33217">as</a><a rel="noreferrer noopener" href="https://blog.finxter.com/python-in-place-assignment-operators/" data-type="post" data-id="33217" target="_blank">s</a><a href="https://blog.finxter.com/python-in-place-assignment-operators/" data-type="post" data-id="33217">ign</a> the whole return value to the variable. For example, the expression <code>my_result = eval('2+2')</code> stores the result <code>4</code> in the variable <code>my_result</code>. </p>
<p>Here’s a minimal example:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">my_result = eval('2+2')
print(my_result)
# 4
</pre>
<p>This simple approach may not always work, for example, if you have a <code>print()</code> statement in the expression. </p>
<p>Read on to learn how to fix this issue next and learn something new!</p>
<h2>Method 2: Redirect Standard Output</h2>
<p>This method assumes you have a <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank">print()</a></code> statement within the expression passed into the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-eval/" data-type="post" data-id="19204" target="_blank">eval()</a></code> function such as shown in the following three examples:</p>
<ul>
<li><code>eval('print(2+2)')</code></li>
<li><code>eval('print([1, 2, 3, 4] + [5, 6])')</code></li>
<li><code>eval('print(2+2*0)')</code></li>
</ul>
<p>To get the output and store it in a variable <code>my_result</code>, you need to temporarily <a href="https://blog.finxter.com/7-easy-steps-to-redirect-your-standard-output-to-a-variable-python/" data-type="post" data-id="365385" target="_blank" rel="noreferrer noopener">redirect the standard output</a> to the variable. </p>
<p>The following code shows you how to accomplish exactly this:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="15-16" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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 world
</pre>
<p>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.</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f440.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Related Article:</strong> <a href="https://blog.finxter.com/7-easy-steps-to-redirect-your-standard-output-to-a-variable-python/" data-type="post" data-id="365385">7 Easy Steps to Redirect Your Standard Output to a Variable (Python)</a></p>
<p>Note that this approach even works if you don’t have a <code>print()</code> statement in the original <code>eval()</code> expression because you can always artificially add the <code>print()</code> statement around the original expression like so:</p>
<ul>
<li><code>eval('2+2')</code> becomes <code>eval('print(2+2)')</code></li>
<li><code>eval('2+2*0')</code> becomes <code>eval('print(2+2*0)')</code></li>
<li><code>eval('[1, 2, 3] + [4, 5]')</code> becomes <code>eval('print([1, 2, 3] + [4, 5])')</code></li>
</ul>
<p>Even if it’s a bit clunky, after applying this short trick, you can redirect the standard output and store the result of <strong><em>any</em></strong> <code>eval()</code> expression in a variable.</p>
<h2>Method 3: Use exec()</h2>
<p class="has-global-color-8-background-color has-background">Using only Python’s <code>eval()</code> function, you cannot define variables inside the expression to be evaluated. However, you <em>can </em><strong>define a variable inside the <code>exec()</code> function</strong> that will then be added to the global namespace. Thus, you can access the defined variable in your code after termination of the <code>exec()</code> expression!</p>
<p>Here’s how that works in a minimal 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="">exec('my_result = 40 + 2')
print(my_result)
# 42</pre>
<p>Variable <code>my_result</code> is only defined in the string expression passed into <code>exec()</code>, but you can use it in the code like it was part of the original source code.</p>
<h2>Recap 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>
<p>You can learn more about the <code>exec()</code> function here:</p>
<ul>
<li><strong>Related Article:</strong> <a href="https://blog.finxter.com/python-exec/" data-type="post" data-id="18860" target="_blank" rel="noreferrer noopener">Python <code>exec()</code> — A Hacker’s Guide to A Dangerous Function</a></li>
</ul>
<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">
<iframe loading="lazy" title="Python exec() — A Hacker’s Guide to A Dangerous Function" width="780" height="439" src="https://www.youtube.com/embed/DHpDA4QDGiU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<h2>Where to Go From Here?</h2>
<p>Enough theory. Let’s get some practice!</p>
<p>Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. </p>
<p>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?</p>
<p><strong>You build high-value coding skills by working on practical coding projects!</strong></p>
<p>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?</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f680.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> If your answer is <strong><em>YES!</em></strong>, consider becoming a <a rel="noreferrer noopener" href="https://blog.finxter.com/become-python-freelancer-course/" data-type="page" data-id="2072" target="_blank">Python freelance developer</a>! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>If you just want to learn about the freelancing opportunity, feel free to watch 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 learn 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>
</div>


https://www.sickgaming.net/blog/2022/05/...-variable/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016