ets-labs/python-dependency-injector

Can't get contextmanager-style resource to work:

Closed this issue · 3 comments

Running version 4.43.0

No combination of calling the provider, or calling init_resources before or after calling the provider calls the __enter__ method. shutdown_resources doesn't work either:

In [22]: from dependency_injector import containers, providers
    ...: 
    ...: class DatabaseConnection:
    ...:     def __init__(self):
    ...:         self.connected = False
    ...: 
    ...:     def __enter__(self):
    ...:         print(f"Connecting db")
    ...:         self.connected = True
    ...:         return self
    ...: 
    ...:     def __exit__(self, exc_type, exc_val, exc_tb):
    ...:         print("Closing connection")
    ...:         self.connected = False
    ...: 
    ...: 
    ...: class Container(containers.DeclarativeContainer):
    ...: 
    ...:     config = providers.Configuration()
    ...:     db = providers.Resource(
    ...:         DatabaseConnection,
    ...:     )
    ...: 

In [23]: c = Container()

In [24]: c.db()
Out[24]: <__main__.DatabaseConnection at 0x7cb818aa2180>

In [25]: c.init_resources()

In [26]: c = Container()

In [27]: c.init_resources()

In [28]: c.db()
Out[28]: <__main__.DatabaseConnection at 0x7cb7e6116210>

In [29]: c.db().connected
Out[29]: False

In [30]: c.db.init().connected
Out[30]: False

In [31]: c = Container()

In [32]: c.init_resources()

function-type resources work fine, but I don't think they can be shutdown. Creating a contextmanager from a function with @contextlib.contextmanager doesn't work either.

Tested with the latest version, can't get that to work either

Context manager support was introduced in v4.48.0.

Your options are either:

Tested with the latest version, can't get that to work either

With v4.48.1 (latest version) I'm getting the following:

In [2]: c = Container()

In [3]: c.db()
Connecting db
Out[3]: <__main__.DatabaseConnection at 0x73276c244590>

In [4]: c.init_resources()

In [5]: c = Container()

In [6]: c.init_resources()
Connecting db

In [7]: c.db()
Out[7]: <__main__.DatabaseConnection at 0x73276c3d8440>

In [8]: c.db().connected
Out[8]: True

In [9]: c.db.init().connected
Out[9]: True

In [10]: c = Container()

In [11]: c.init_resources()
Connecting db