ivankorobkov / python-inject

Python dependency injection
Apache License 2.0
671 stars 77 forks source link

Added context manager condition to attr function(Fix #94) #96

Closed fhdufhdu closed 3 months ago

fhdufhdu commented 3 months ago
class SyncCM:
    def __init__(self, i):
        self.i = i
    def __enter__(self):
        print('enter')
        return self
    def __exit__(self, *args):
        print('exit')
        return self
    def test(self, j: int):
        return j

@contextmanager
def get_cm() -> Iterator[object]:
    with SyncCM(10) as cm:
        yield cm

class Repo:
    _cm:SyncCM = inject.attr(SyncCM)

    def cm_test(self):
        result = self._cm.test(20)
        return result

def configure(binder:inject.Binder):
    binder.bind_to_provider(SyncCM, get_cm)

inject.configure(configure)

r:Repo = inject.instance(Repo)
result = r.cm_test()
print(result)

Resolved the error occurring(#94) when using @contextmanager in the parameter function of .bind_to_provider function

@contextmanager: Resolved @asynccontextmanager: Replaced with an Exception since a way to use Descriptors asynchronously could not be found.

ivankorobkov commented 3 months ago

Thanks.

I have just released https://pypi.org/project/inject/5.2.1/

fhdufhdu commented 3 months ago

@ivankorobkov Thanks!