Python equivalents

Decorators

def add1(x): return x+1
add1(3)
4

A function that returns a function:

def logargs(f):
    "Print arguments to `f` before calling it"
    def _inner(*args, **kwargs):
        print(f"Received: {args=}; {kwargs=}")
        return f(*args, **kwargs)
    return _inner

Using logargs to modify a function:

def _mult2(x): return x*2
mult2 = logargs(_mult2)
mult2(3)
Received: args=(3,); kwargs={}
6

Exactly the same thing but using a decorator as syntax sugar:

@logargs
def mult2(x): return x*2
mult2(3)
Received: args=(3,); kwargs={}
6

A class that takes a function and returns a function:

class logargs:
    def __init__(self, prefix='Received: '): self.prefix=prefix
    def __call__(self, f):        
        def _inner(*args, **kwargs):
            print(f"{self.prefix}{args=}; {kwargs=}")
            return f(*args, **kwargs)
        return _inner

Here’s how to use it:

def _add1(x): return x+1
o = logargs('Logging: ')
add1 = o(_add1)
add1(3)
Logging: args=(3,); kwargs={}
4

Exactly the same thing but using a decorator as syntax sugar:

@logargs('Logging: ')
def add1(x): return x+1
add1(3)
Logging: args=(3,); kwargs={}
4

partial

from functools import partial
def pow(x,y): return x**y
pow(3,2)
9
squared = partial(pow, y=2)
squared(3)
9