# How can we define a Python function at runtime?

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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

Updated on 26-Sep-2019 18:52:00

Advertisements