adriangb / di

Pythonic dependency injection
https://www.adriangb.com/di/
MIT License
301 stars 13 forks source link

feat: add `variance` param to Container.register_by_type #56

Closed adriangb closed 2 years ago

adriangb commented 2 years ago

To allow binding to "any superclass" (contravariant) or "any subclass" (covariant). Maybe there's better nomenclature for this...

Use case for covariance:

class App:
     def __init__(self):
         ...
         self.container.register_by_type(Dependant(lambda: self), App, covariant=True)

class UsersCustomApp:
    pass

def dep(app: App):. ...

And dep should have the UsersCustomApp instance injected.

Another use case: users want to override the "Request" class used.

contravariant is a bit trickier: not sure why we'd want it, and it would need some sort of bound: type argument. So maybe let's punt on that one.