Python function wrapper

Content:

Another Python finesse seen on LinkedIn

First some standard code.

def f1():
    """This is really f1"""
    print('f1')

def f2():
    """This is really f2"""
    print('f2')

def dof(f):
    print(f.__name__ + ' (' + f.__doc__ + ') says:')
    f()

dof(f1)
dof(f2)

Output:

f1 (This is really f1) says:
f1
f2 (This is really f2) says:
f2

Now we wrap the function.

def entext(func):
    def wrapper(*args, **kwargs):
        """This is really wrapper"""
        print('enter')
        func(*args, **kwargs)
        print('exit')
    return wrapper

@entext
def f1():
    """This is really f1"""
    print('f1')

@entext
def f2():
    """This is really f2"""
    print('f2')

def dof(f):
    print(f.__name__ + ' (' + f.__doc__ + ') says:')
    f()

dof(f1)
dof(f2)

Output:

wrapper (This is really wrapper) says:
enter
f1
exit
wrapper (This is really wrapper) says:
enter
f2
exit

Now we fix the function meta data using @wraps.

from functools import wraps

def entext(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        """This is really wrapper"""
        print('enter')
        func(*args, **kwargs)
        print('exit')
    return wrapper

@entext
def f1():
    """This is really f1"""
    print('f1')

@entext
def f2():
    """This is really f2"""
    print('f2')

def dof(f):
    print(f.__name__ + ' (' + f.__doc__ + ') says:')
    f()

dof(f1)
dof(f2)

Output:

f1 (This is really f1) says:
enter
f1
exit
f2 (This is really f2) says:
enter
f2
exit

Maybe not super important, but still interesting.

Comments: