Creating very similar functions with different parameters

Ian Kelly ian.g.kelly at gmail.com
Tue Oct 25 10:40:48 EDT 2011


On Mon, Oct 24, 2011 at 3:29 PM, Andrew Berg <bahamutzero8825 at gmail.com> wrote:
> I want to create a decorator with two different (but very similar)
> versions of the wrapper function, but without copying giant chunks of
> similar code. The main difference is that one version takes extra
> parameters.
>
> def test_dec(func, extra=False):
>        if extra:
>                def wrapper(ex_param1, ex_param2, *args, **kwargs):
>                        print('bla bla')
>                        print('more bla')
>                        print(ex_param1)
>                        print(ex_param2)
>                        func(ex_param1, ex_param2, *args, **kwargs)
>        else:
>                def wrapper(*args, **kwargs):
>                        print('bla bla')
>                        print('more bla')
>                        func(*args, **kwargs)
>        return wrapper
>
> If the function I'm wrapping takes ex_param1 and ex_param2 as
> parameters, then the decorator should print them and then execute the
> function, otherwise just execute the function. I'd rather not write
> separate wrappers that are mostly the same.

Others have given more involved suggestions, but in this case you
could just make the wrapper a closure and check the flag there:

def test_dec(func, extra=False):
    def wrapper(*args, **kwargs):
        print('bla bla')
        print('more bla')
        if extra:
            ex_param1, ex_param2 = args[:2]
            print(ex_param1)
            print(ex_param2)
        func(*args, **kwargs)
    return wrapper

Cheers,
Ian



More information about the Python-list mailing list