Open In App
Related Articles

Defining a Python function at runtime

Improve Article
Improve
Save Article
Save
Like Article
Like

In Python,we can define a python function at runtime execute with the help of FunctionType(). First we import types module then perform compile() function and pass parameter exec and after that with the help FunctionType() define the function at runtime.

Example 1: Function to print GEEKSFORGEEKS.

Python3




# importing the module
from types import FunctionType
  
# functttion during run-time
f_code = compile('def gfg(): return "GEEKSFORGEEKS"', "<string>", "exec")
f_func = FunctionType(f_code.co_consts[0], globals(), "gfg")
  
# calling the function
print(f_func())


Output:

GEEKSFORGEEKS

Example 2: Function to add 2 numbers.
 

Python3




# importing the module
from types import FunctionType
  
# function at run-time
f_code = compile('def gfg(a, b): return(a + b) ', "<int>", "exec")
f_func = FunctionType(f_code.co_consts[0], globals(), "gfg")
  
val1 = 3999
val2 =4999
  
# calliong the function
print(f_func(val1, val2))


Output: 

8998
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 29 Dec, 2020
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials