Creating very similar functions with different parameters

Andrew Berg bahamutzero8825 at gmail.com
Mon Oct 24 17:29:25 EDT 2011


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.

-- 
CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0



More information about the Python-list mailing list