Skip to content

Instantly share code, notes, and snippets.

@bluesquall
Created September 27, 2012 19:09
Show Gist options
  • Select an option

  • Save bluesquall/3795830 to your computer and use it in GitHub Desktop.

Select an option

Save bluesquall/3795830 to your computer and use it in GitHub Desktop.
A useful method for passing named arguments with defaults to a SuperClass without having to write name=name for each argument in the call to the SuperClass method. I feel like this should already exist in the standard library, but I didn't find anythi
#!/usr/bin/env python
"""A useful method for passing named arguments with defaults to a SuperClass
without having to write name=name for each argument in the call to the
SuperClass method.
I feel like this should already exist in the standard library, but I didn't
find anything like it with a quick search.
"""
def injectlocals(l, skip=['self','args','kwargs'], **kwargs):
"""Update a dictionary with another, skipping specified keys."""
if l.has_key('kwargs') : kwargs.update(l['kwargs'])
kwargs.update(dict((k, v) for k, v in l.items() if k not in skip))
return kwargs
class SuperClass(object):
def printthings(self, *args, **kwargs):
for k, v in kwargs.items(): print 'key:', k, 'value:', v
class SubClass(SuperClass):
def printthings(self, a=1, b=42, *args, **kwargs):
SuperClass.printthings(self, **injectlocals(locals()))
if __name__ == "__main__":
kwargs = {'foo': 'bar'}
print '\nby SuperClass:'
SuperClass().printthings(**kwargs)
print '\nby SubClass:'
SubClass().printthings(**kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment