Created
September 2, 2013 19:45
-
-
Save macobo/6416625 to your computer and use it in GitHub Desktop.
Dependency injection in python
This file contains hidden or 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
| import inspect | |
| from functools import wraps | |
| def inject(function): | |
| @wraps(function) | |
| def inner(**kwargs): | |
| original_args_list = inspect.getargspec(function).args | |
| undefined = [arg for arg in original_args_list if arg not in kwargs] | |
| if undefined: | |
| raise Exception("We don't know what to do with "+str(undefined)) | |
| star_args = [kwargs[arg] for arg in original_args_list] | |
| return function(*star_args) | |
| return inner | |
| if __name__ == "__main__": | |
| @inject | |
| def foo(bar, baz): return bar + baz | |
| assert foo(some_undefined=5, baz="baz", bar="bar") == "barbaz" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment