Python Exec() with Syntax and Examples

Do you remember that fairy basket?

Nevertheless, it has so much knowledge to give, but it has one rule, one thing at a time.

And today’s secret of this basket is something Dynamic.

Not taking too much time to learn this new spell, here I introduce to you Exec() function, and of course, our buddy Python is going to do it all for us again. So let’s learn about Python Exec().

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

What is Exec() function in Python?

Exec() function’s usage is for the dynamic execution of a Python program, which can either be a string or object code in user-defined runtime.

Do you think it is the same as Eval? Of course not.

Did you read it is used for dynamic execution of code? It works on the principle of the dynamic execution of code, which makes it very different from Eval.

What does this mean?

This means if it is a string, the string is parsed as a suite of Python statements and then it is executed.

If it is an object code, it is simply executed in a well-defined manner for any integral value in a code.

And one needs to keep in mind that the return statements may not be used outside of function definitions.

Neither even within the context of code which is passed to the exec() function.

This means if it is a string, it simply doesn’t return any value, hence displays ‘none’.

Python Exec() Syntax

The syntax of exec() is

exec(object[, globals[, locals]])

Like a choosy designer who accepts only perfect fabric to make a completely lavish robe, exec() does not take everything which is assigned to it.

Parameters of Exec() in Python

  • Object: It can be a string or object code.
  • Globals: This is a dictionary and the parameter is optional.
  • Locals: It can be a mapping object and is also optional.

Globals and Locals Parameters in Python Exec()

Using globals and locals parameters in user-specific codes, a coder can restrict what variables and methods the users can access in runtime.

One can either provide both or just the globals, in such a case that value suffices for both- globals and the local variables can be parsed.

At the module level, globals and locals are the same dictionaries.

Python Exec() Example

>>> exec('print(tan(45))')

Output

>>> 1

Example of Python Exec() Function

from math import 
exec('print(fact(5))', {'fact': factorial}) 
#factorial re-coded as (fact)

Output

120

When should we use Exec in Python?

As a side effect, implementation of exec() may insert additional keys into dictionaries.

Besides, the code corresponds to variable names and is set by the executed code.

Python Exec Example

a=int(input(“enter a number”))
if: 
  a= 8
  exec('print(a==8)') 
   If true:
  
       exec('print(a+3)')

Output

True
11

Statement Evaluation by Exec()

Not only the integers, strings, as earlier mentioned, can get evaluated by exec() function. Here is an example of the same:

Python Exec Function Example

for i in range(5):\n  
print('Hello world!')

Output

Hello world!
Hello world!
Hello world!
Hello world!
Hello world!

Warnings while using Python Exec()

Sometimes it happens when the coder uses a Unix system (macOS, Linux etc) or has simply imported an os module.

The os module provides a static way in user defined codes to use operating system functionalities such as the read library and appending a file.

Exec() Vs Eval() in Python

Eval accepts a single expression while exec operates on Python statements: loops, try: except:, class and function/method definitions in runtime.

An expression is whatever you can have as the value irrespective of its original domain in the variable assignment of the code.

Eval() returns the value of the given expression, whereas exec ignores the return value from its code, and always returns none in runtime.

Whereas in ‘eval’ mode, it compiles a single expression into the bytecode that returns user-specific value of that expression. In the ‘eval’ mode the compiler raises an exception in runtime if the source code contains statements that are user static and are also beyond a single expression for any integral value in a code in a definite runtime.

Restricting Usage of Available Methods and Variables in Exec()

If both, parameters are being omitted for user-specific codes, the code executed by exec() is executed in the current scope location of the library having any integral or variable value.

The globals and locals parameters (basically dictionaries) are used for global and local variables respectively.

If a local dictionary is omitted, it defaults to the globals dictionary. If the coder passes an empty dictionary as globals for the search, then only the built-ins are available to the object (the first parameter to the exec()) in runtime.

Summary

Unlike any other programming language, python has a lot to offer to its coders, with the ease and efficiency function is actually what gives its coders the best in python.

Exec() being one of them makes it so much easier for the coder to evaluate string/integer in a simple manner.

But unlike any other function, it performs dynamic real-time execution, which can be either for a string or a code.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.