What does eval() do in Python?

I have always loved the fact that The Python interpreter has a number of functions and types built into it. I am going to explore “eval()” in this article.

Syntax: eval(expression[, globals[, locals]])
or
eval(expr, globals=None, locals=None)

So, mainly eval need string as its argument in expression.

globals (optional)Global namespace to use while executing the source. It must be a dictionary. If not provided then the current global namespace will be used.
locals (optional)Local namespace to use while executing the source. It can be any mapping. If omitted, it defaults to globals dictionary.

You can check globals and locals by global() and locals().

Example

def display(users_name):
    return "Hello " + users_name + " !"

names = [
    "Fahad Ahammed", "Guido Van Rossum"
]

for i in names:
    print(eval(f'display("{i}")'))

The output will be –

Hello Fahad Ahammed !
Hello Guido Van Rossum !

Isn’t it cool? 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.