Lancetnik / FastDepends

FastDepends - FastAPI Dependency Injection system extracted from FastAPI and cleared of all HTTP logic. Async and sync modes are both supported.
https://lancetnik.github.io/FastDepends/
MIT License
254 stars 9 forks source link

Use in class #34

Closed chrisgoddard closed 7 months ago

chrisgoddard commented 7 months ago

Hi there!

Quick question - is there a way to use this in the context of a class rather than a function?

Either within a method:

class Example:
    @inject
    def method(self, x = Depends(dependency)):
        ...

or class variable?

@inject
class Example:
    x = Depends(dependency)

    def method(self):
        ...

Right now, in the first example, I get the error TypeError: CallModel.solve() got multiple values for argument 'self'

(second example was just another idea - not expected behavior).

Love the library btw - thanks!

Lancetnik commented 7 months ago

I didn't think about classes support at all, but it sounds like a good idea. I'll try to implement the first example, thank you!

chrisgoddard commented 7 months ago

Awesome - I'm curious whether that would also work if @inject decorated the init method - it would be really cool to be able to do injection into class constructors

Lancetnik commented 7 months ago

@chrisgoddard the job is done

from fast_depends import Depends, inject

def _get_var():
    return 1

class Class:
    @inject
    def __init__(self, a = Depends(_get_var)) -> None:
        self.a = a

    @inject
    def calc(self, a = Depends(_get_var)) -> int:
        return a + self.a

def test_class():
    assert Class().calc() == 2

Thanks for the idea. Seems like FastDepends can be used as a full-featured DI library. You inspired me to improve this project next)

chrisgoddard commented 7 months ago

Now that's a turnaround!! Thanks mate!

chrisgoddard commented 7 months ago

FYI #37