Thursday 15 September 2011

dependency injection - Can Python do DI seamlessly without relying on a service locator? -



dependency injection - Can Python do DI seamlessly without relying on a service locator? -

i'm coming c# world, views may little skewed. i'm looking di in python, i'm noticing trend libraries appear rely on service locator. is, must tie object creation framework, such injectlib.build(myclass) in order instance of myclass.

here illustration of mean -

from injector import injector, inject class inner(object): def __init__(self): self.foo = 'foo' class outer(object): @inject(inner=inner) def __init__(self, inner=none): if inner none: print('inner not provided') self.inner = inner() else: print('inner provided') self.inner = inner injector = injector() outer = outer() print(outer.inner.foo) outer = injector.get(outer) print(outer.inner.foo)

is there way in python create class while automatically inferring dependency types based on parameter names? if have constructor parameter called my_class, instance of myclass injected. reason inquire don't see how inject dependency class gets created automatically via 3rd party library.

to reply question explicitly asked: no, there's no built-in way in python automatically myclass object parameter named my_class.

that said, neither "tying object creation framework" nor illustration code gave seem terribly pythonic, , question in general kind of confusing because di in dynamic languages isn't big deal.

for general thoughts di in python i'd this presentation gives pretty overview of different approaches. specific question, i'll give 2 options based on might trying do.

if you're trying add together di own classes, utilize paramaters default values in constructor, presentation shows. e.g:

import time class example(object): def __init__(self, sleep_func=time.sleep): self.sleep_func = sleep_func def foo(self): self.sleep_func(10) print('done!')

and pass in dummy sleep function testing or whatever.

if you're trying manipulate library's classes through di, (not can imagine utilize case for, seems you're asking) monkey patch classes alter whatever needed changing. e.g:

import test_module def dummy_sleep(*args, **kwargs): pass test_module.time.sleep = dummy_sleep e = test_module.example() e.foo()

python dependency-injection

No comments:

Post a Comment