Skip to content

Instantly share code, notes, and snippets.

@rjwebb
Last active April 11, 2017 23:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjwebb/8cf99b7af727a3b5007bc71450c5520b to your computer and use it in GitHub Desktop.
Save rjwebb/8cf99b7af727a3b5007bc71450c5520b to your computer and use it in GitHub Desktop.
(not serious)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python dependency injection experiment!!
# Provides a DependencyScope object which lets you declare
# dependencies and inject them in functions à la AngularJS
class DependencyScope:
def __init__(self):
self.dependencies = {}
def register(self, name=''):
def register_inner(func):
self.dependencies[name] = func
return func
return register_inner
def inject(self, deps=[]):
def inject_inner(func):
def f(*args, **kwargs):
for d in deps:
# Try to get registered dependency
try:
dep = self.dependencies[d]
except KeyError:
# Otherwise is it a Python pkg?
dep = __import__(d)
kwargs[d] = dep
return func(*args, **kwargs)
return f
return inject_inner
scope = DependencyScope()
# This uses the 'requests' library -
# make sure you have it installed
@scope.register(name='print_content_dep')
@scope.inject(deps=['requests'])
def print_content(url, requests=None):
r = requests.get(url)
print(r.content)
@scope.inject(deps=['print_content_dep'])
def test(print_content_dep=None):
print_content_dep('https://www.theguardian.com/uk')
print(scope.dependencies)
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment