makefun library

1.16.0 · active · verified Sun Apr 05

makefun is a small Python library for dynamically creating functions and modifying existing function signatures at runtime. It is currently at version 1.16.0 and maintains an active development cycle with regular updates, including support for new Python versions and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core functionalities: creating a new function with `create_function` by specifying its signature and implementation, and wrapping an existing function while modifying its signature using the `wraps` decorator.

from makefun import create_function, wraps
from inspect import Signature, Parameter

# Example 1: Creating a function from scratch
def my_implementation(a, b):
    return f"a={a}, b={b}"

sig = Signature([
    Parameter('a', Parameter.POSITIONAL_OR_KEYWORD),
    Parameter('b', Parameter.POSITIONAL_OR_KEYWORD, default=2)
])

dynamic_func = create_function(sig, my_implementation, doc="A dynamically created function")
print(dynamic_func(1)) # Output: a=1, b=2
print(dynamic_func(10, b=20)) # Output: a=10, b=20

# Example 2: Wrapping an existing function and changing its signature
def original(x, y):
    return x * y

@wraps(original, new_sig=Signature([Parameter('val', Parameter.POSITIONAL_OR_KEYWORD)]))
def my_wrapper(val):
    # original expects x, y. Let's map 'val' to both.
    return original(val, val)

print(my_wrapper(val=5)) # Output: 25

view raw JSON →