Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How can we define a Python function at runtime?

I have a script with a function as follows

#dyn.py
def dynf()
     print “Really Works”

I want to define the same python function and execute it at runtime by using the python prompt. How do I do that?


1 Answer
Rajendra Dharmkar

We can define a python function and execute it at runtime by importing the types module and using its function types.FunctionType() as follows

This code works at the python prompt as shown. First we import the types module. Then we run the command dynf=…; then we call the function dynf() to get the output as shown

>>> import types
>>> dynf = types.FunctionType(compile('print "Really Works"', 'dyn.py', 'exec'), {})
>>> dynf()
Really Works

 

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.