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:
- function code is stored as a string in **func.
- **exec(func) executes the string, defining **fun at runtime.
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:
- **compile() compiles Python code dynamically.
- **exec() executes the compiled code in a separate namespace ****(d)**.
- function is retrieved from the dictionary and used dynamically.
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:
- we define **fun at runtime based on user input
- if the input is "**add", the function performs addition and if "**multiply", it performs multiplication.
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:
- **fun(n) defines a function at runtime that multiplies its input by n.
- **multiplier(x) captures n from the enclosing scope.
- generate new functions dynamically ****(mul_3, mul_5)** with different behaviors.