Defining a Python Function at Runtime (original) (raw)

Last Updated : 27 Feb, 2025

One amazing feature of Python is that it lets us create functions while our program is running, instead of just defining them beforehand. This makes our code more flexible and easier to manage. It’s especially useful for things like metaprogramming, event-driven systems and running code dynamically as needed.

There are several ways to define a function at runtime, let's explore them one by one:

Using exec

exec() function allows us to execute dynamically created code as a string so that it can be used to define functions at runtime.

Python `

fun = """ def func(name): return f"Hello, {name}!" """

exec(fun)

Now we can call the dynamically created function

print(func("Geeks"))

`

**Explanation:

Using types.FunctionType

Python’s types module has some handy tools for creating functions while your program is running, like FunctionType. This is useful when you need to change functions as your program runs or even build them from scratch using bytecode and with the help of compile() function, we can turn a string into code that Python understands, then run it using exec() and save the function for later in a dictionary.

Python `

import types

code = compile("def greet(name): return f'Hello, {name}!'", "", "exec")

d = {} exec(code, d) # Execute the compiled code in a separate namespace

msg = d["greet"] # Retrieve the function from the namespace

print(msg("Geeks"))

`

**Explanation:

Using Lambda

Lambda functions allows us to create small, anonymous functions dynamically at runtime.

Python `

operation = input("Enter operation (add/multiply): ")

if operation == "add": fun = lambda x, y: x + y elif operation == "multiply": fun = lambda x, y: x * y else: fun = lambda x, y: "Invalid operation"

print(fun(5, 3)) # Output depends on user input

`

**Explanation:

Using Closures

Closures let us create functions inside other functions while keeping access to local variables. This means you can generate specific functions as needed without affecting the rest of your code.

They’re especially useful for creating function factories, decorators and custom functions as the program runs. Here’s an example:

Python `

def fun(n): """Returns a function that multiplies input by 'n'.""" def multiplier(x): return x * n return multiplier # Return the dynamically created function

mul_3 = fun(3) mul_5 = fun(5)

print(mul_3(4)) print(mul_5(4))

`

**Explanation: