How can we define a Python function at runtime?

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()

Output

Really Works

 

Defining a Python function at runtime can be useful in a variety of situations, such as when you need to create functions dynamically based on user input or configuration settings. In this section, I will provide several examples of how you can define functions at runtime in Python.

Defining a simple function with a fixed signature

The simplest way to define a function at runtime is to use the lambda keyword to create a new function object. Here's an example:

# Define a function at runtime using lambda
add = lambda a, b: a + b

# Call the function
result = add(1, 2)
print(result) 

Output

3
 

In this example, we define a new function called add using a lambda expression that takes two arguments a and b and returns their sum. We can then call the function like any other function.

Defining a function with a variable signature

If you need to define a function with a variable number of arguments, you can use the *args and **kwargs syntax to capture variable-length argument lists and keyword arguments, respectively. Here's an example:

# Define a function with a variable signature
def make_adder(*args, **kwargs):
    def adder(x):
        return sum(args) + sum(kwargs.values()) + x
    return adder

# Define a new function at runtime
add_1 = make_adder(1)
add_2 = make_adder(2, 3, 4)
add_3 = make_adder(a=1, b=2, c=3)

# Call the functions
result_1 = add_1(10)
result_2 = add_2(10)
result_3 = add_3(10)

print(result_1) 
print(result_2) 
print(result_3) 

Output

11
19
16
 

In this example, we define a higher-order function called make_adder that takes a variable number of arguments using *args and **kwargs. The function returns a new function that takes a single argument x and returns the sum of its arguments along with x.

We then define several new functions at runtime by calling make_adder with different arguments. Each of these functions has a different signature and will behave differently when called.

Defining a function with a closure

A closure is a function that captures the state of its enclosing scope at the time it is defined. You can use closures to define functions that have access to variables defined outside of their own scope. Here's an example:

# Define a function with a closure
def make_multiplier(factor):
    def multiplier(x):
        return factor * x
    return multiplier

# Define a new function at runtime
double = make_multiplier(2)
triple = make_multiplier(3)

# Call the functions
result_1 = double(10)
result_2 = triple(10)

print(result_1) 
print(result_2) 

Output

20
30
 

In this example, we define a higher-order function called make_multiplier that takes a single argument factor. The function returns a new function called multiplier that takes a single argument x and returns the product of x and factor.

We then define two new functions at runtime by calling make_multiplier with different arguments. Each of these functions captures the value of factor at the time it was defined and will use this value whenever it is called.

Defining a function with a dynamic name

You can also define a function at runtime with a dynamic name using the globals() or locals() functions to update the global or local namespace with the new function. Here's an example:

# Define a function with a dynamic name
def make_function(name, x):
    def function():
        return x * x
    globals()[name] = function

# Define a new function at runtime
make_function('square', 2)

# Call the function
result = square()
print(result)

Output

4
 

In this example, we define a higher-order function called make_function that takes two arguments: a name for the new function and a value x. The function defines a new function called function that returns the square of x.

We then call make_function with the name 'square' and the value 2, which creates a new function called square in the global namespace using globals().

Defining a function with a decorator

Finally, you can define a function at runtime by decorating an existing function with a dynamically generated decorator function. Here's an example:

# Define a decorator function that adds logging
def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f'Calling function {func.__name__} with arguments {args} and {kwargs}')
        return func(*args, **kwargs)
    return wrapper

# Define a function at runtime using a decorator @log_calls
@log_calls
def my_function(x, y):
    return x + y

# Call the function
result = my_function(1, 2)
print(result)

Output

Calling function my_function with arguments (1, 2) and {}
3
 
Updated on: 2026-03-12T21:19:41+05:30

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements