Here's a decorator, inspired to some degree by the one in a recipe titled Keyword Argument Injection with Python Decorators, that might help. It certainly cuts down on the repetition, maybe too much.
import sys
def injectlocalargs(inFunction):
def outFunction(*args, **kwargs):
# get decorated function's argument names
func_argnames = inFunction.func_code.co_varnames
# caller's local namespace
namespace = sys._getframe(1).f_locals
# add values of any arguments named in caller's namespace
kwargs.update([(name,namespace[name]) for name in func_argnames if name in namespace])
# call decorated function and return its result
return inFunction(*args, **kwargs)
return outFunction
##### testbed #####
class template_class:
@injectlocalargs
def render(self, extra_stuff, current_user, thread, messages):
print 'render() args'
print ' extra_stuff:%s, current_user:%s, thread:%s, messages:%s' % (extra_stuff, current_user, thread, messages)
def test():
current_user = 'joe'
thread = 42
messages = ['greetings',"how's it going?"]
template = template_class()
template.render('extra_stuff')
test()
Output:
render() args
extra_stuff:extra_stuff, current_user:joe, thread:42, messages:['greetings', "how's it going?"]