exec() in Python
Overview
The program, which can be a string or a code object, is executed using the exec() method. Python exec() function accepts code in the form of a string or an object code and then executes it.
Use of Python exec() Function :
Python exec() function is used in the case when we run the program. Now the question is how? So, the python exec() function replaces the current processing image with the one you have just started.
Syntax for Python exec() Function :
Python exec() function takes 3 parameters: objects, globals, and locals. We will discuss those parameters further.
Parameters of Python exec() Function :
The python exec() function takes three parameters below.
- object :
It is the required one parameter. It can be either a string or a code object. This object provides the code or string to the exec() function for further execution. - globals :
It is an optional parameter. It is a dictionary of available global methods and variables. These globals provide the global methods and variables to the exec() function if needed. - locals :
It is an optional parameter, a dictionary of available local methods and variables. These locals provide the local methods and variables to the exec() function if needed.
Return Value of Python exec() Function :
exec() the function doesn't return any value, it returns None. So outside of function declarations, we can't use return and yield statements.
When Using Python exec() Function, Be Cautious
Let's pretend we're working on a Unix system like MacOS, Linux, or others, and we've imported a os module. This 'os' module now gives you a flexible approach to operating system functionalities, including reading and writing files. If you allow users to use exec(input()) to enter a value, they can execute the command os.system('rm -rf *') to modify, alter, or even remove all of the OS's files.
Furthermore, you should never send exec to an untrustworthy source() because it is quite easy for a rogue user to wreak havoc on the system.
Example
The example below will make you more clear with this exec() function.
Code :
Output :
In the above example, demo_lst is a string that is then parsed into a python statement and executed. Here we notice that we haven't defined "demo_lst" in the code other than that string inside exec(). It shows that the exec() function executes that string and thus feeds up that demo_lst in python IDE during runtime, which is printed further.
What is exec() in Python?
The exec function is used to execute a python code that can either be a string or a code. If it's a string, it's parsed or processed into a sequence of Python statements, which are then performed until there's a syntax error. If it's a code, it is interpreted as python code for errors and is immediately executed.
Tips:
- We must not use return statements outside of function declarations, and we must not use them in the scope of code provided to the exec function because exec() doesn't return any value, it returns None. So we can't use return and yield statements outside the function declaration.
- When invoking any methods within the exec function, it is important to remember which functions exec allows. To learn about those available functions, run the code given below.
Code :
Output :
So the above list contains all the functions we can use inside the exec() method.
How to Use an exec() in Python?
As shown previously in the example, for using this exec() function, we just have to pass the python program in the string or object format inside the exec() function.
More Examples
Example - 1 : How exec() Works ?
Code :
Output :
The above program is executed using the string object program, provided to exec(). In this situation, globals and locals are not used.
In the above program, the function sample() is defined inside the exec() method, which feeds that sample() function in python IDE during runtime for further access.
Example - 2: Allow User to Provide Input
Code :
Output :
From the above example, it is clear how to take input from the user itself in this exec() function.
Example - 3 : Execute Multi-line Code
Code :
Output :
In the above example, multi-line code is passed as a string to the exec() function, where each code line is considered a statement.
Example - 4 : Importing Modules
Code :
Output :
Here in the above example, it is clear that one can also import the libraries within the string that is passed to the exec() function further and can use the inbuilt functions of that library in the code.
Restricting the Use of Available Methods and Variables in Python exec() Function
Most of the time, all the accessible functions and variables in exec() aren't needed, and some even have a security flaw. You can limit the use of such variables and functions by giving optional globals and local parameters (dictionaries) to the exec() method.
1. Both Globals and Locals Parameters are Omitted
The code expected to be executed by exec() is performed in the current scope if both parameters are omitted( missing ).
2. Passing Globals Parameter, Locals Parameter is Omitted
The global and local parameters are utilized for both global and local variables. If the local dictionary is not specified, the global dictionary is used instead. We can utilize global variables for both global and local variables.
3. Passing Empty Dictionary as Globals Parameter :
Code :
Output :
Only the builtins are available to the object if you provide an empty dictionary as globals. Even if the math module has been imported into the preceding program, any attempt to use any of the math module's functions will result in an exception.
Making Certain Methods Available :
The code below shows that the the exec() function can pass some methods like sqrt() and pow() along with the builtins. Including the sqrt() and pow() function in global dict allows the exec() function to perform those operations otherwise it will throw error.
Output :
By the way, it is also possible to change the name of those methods as done below.
Output :
So in the code above, it will raise an error when trying to use "square root" but will work on "sqrt" because its name is changed.
4. Passing Both Globals and Locals Dictionary
By passing a local dictionary, one could make required functions and variables accessible for use.
So as in the above code, only 3 built-in functions could work are the "print", "dir", and "time". So here we have restricted the use of builtin functions by allowing only some of them inside the local's dict.
Output :
Conclusion
- exec() function takes 3 parameters that is object, globals and locals.
- exec() method returns None.
- Return, and yield can't be used outside function declaration in the exec() method.
- While invoking any function in exec() be sure that it is allowed or not.