Created
September 20, 2015 22:08
-
-
Save manuphatak/e74f1f5197b8947af933 to your computer and use it in GitHub Desktop.
Class decorator that overrides default kwargs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
def defaults(method='__init__', **default_args): | |
"""Class decorator. Overrides method default arguments.""" | |
def decorate(cls): | |
func = getattr(cls, method) | |
@wraps(func) | |
def wrapper(self, *args, **kwargs): | |
default_args.update(kwargs) | |
return func(self, *args, **default_args) | |
setattr(cls, method, wrapper) | |
return cls | |
return decorate |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Overrides defaults without polluting the class namespace.
Defaults can be overridden again at runtime.
For example:
Class
Foo
is equivalent to:More examples:
__init__
. But use themethod
keyword to override any method defaults.