Python Built-in Functions | The eval() Function

preview_player
Показать описание
The arguments are a string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and does not contain a value for the key __builtins__, a reference to the dictionary of the built-in module builtins is inserted under that key before expression is parsed. This means that expression normally has full access to the standard builtins module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed with the globals and locals in the environment where eval() is called. Note, eval() does not have access to the nested scopes (non-locals) in the enclosing environment.

How to develop better habits and write better code?
-- Read more code
-- Write more code
-- Make your code public
-- Be active on Stackoverflow

Read the full article at:

~~~
🐍 Cheating in Python? Of course! 🐍
Become a better coder! Download the 5x Python Cheat Sheet Course (PDF). It’s free!
See you soon -- it’s fun! 🤓
~~~

Experts in their fields read more books! 📚

Each book improves your skills 44% faster (compared to normal Python books) because of our unique puzzle-based learning system.
~~~

Start earning money by creating your own Python coding business (free webinar):

Python Freelancer Course (Six-Figures):
Рекомендации по теме
Комментарии
Автор

I tried running this piece of python code and got this as the output:

print (eval('pow(x, 2)', {'x':4}, {'x':2}))
Output:
4

Why does eval() take x as 2 even when I have provided x as 4
in the global namespace ?

soulfulmelodies-oh