Skip to content

dependency injection into attrs classes with auto_attribs

Notifications You must be signed in to change notification settings

dradetsky/inject-attrs

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 

Repository files navigation

inject_attrs: dep injection into attrs classes

a quick hack around the problem that I want to do dependency injection like

class Thing:
    @inject
    def __init__(self, cfg: Config, some_dep: SomeClass):
        self.cfg = cfg
        self.some_dep = some_dep

But I'd also like to use attrs which allows you to write cool stuff like

@attr.s(auto_attribs=True)
class Thing:
    cfg: Config
    some_dep: SomeClass

Which works fine for manually constructing instances of Thing, but breaks down when you attempt to do dependency injection with Thing, since attrs does not annotate its auto-generated __init__ method.

So now I just write

@inject_attr.s()
class Thing:
    cfg: Config
    some_dep: SomeClass
    
inj = Injector()
t = inj.get(Thing)

t.cfg       # => <Config obj>
t.some_dep  # => <SomeClass obj>

\m/

About

dependency injection into attrs classes with auto_attribs

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages