python-dependency-injector icon indicating copy to clipboard operation
python-dependency-injector copied to clipboard

Broken wiring of sync inject-decorated methods

Open martlaf opened this issue 1 year ago • 4 comments

Hi,

following use case seems broken in versions >= 4.39.0:

from dependency_injector import containers, providers
from dependency_injector.wiring import inject, Provide


class Service:
    @staticmethod
    def run():
        print("hello world!")


class Container(containers.DeclarativeContainer):
    service = providers.Factory(Service)


class MyClass:
    @inject
    def __init__(self, service=Provide[Container.service]):
        service.run()


container = Container()
container.wire(modules=[MyClass])
MyClass()

Output in version 4.38.0:

hello world!

Output in versions >4.38.0

Traceback (most recent call last):
  File "C:\Users\myself\file.py", line 23, in <module>
    MyClass()
  File "src/dependency_injector/_cwiring.pyx", line 28, in dependency_injector._cwiring._get_sync_patched._patched
  File "C:\Users\myself\file.py", line 18, in __init__
    service.run()
AttributeError: 'Provide' object has no attribute 'run'

What seem to happen is that since the _get_sync_patched decorator has been moved to the cython part of the package, the signature of the @inject-decorated func/methods are now cython (type(MyClass.__init__) resolves to cython_function_or_method), therefore inspect.isfunction()/inspect.ismethod() resolve to False, and so those functions are never patched during container wiring.

Might be related to #589.

Finally, I have successfully tested here using the same patch that was applied in 4.39.1 for _get_async_patched coroutine that wasn't properly signed from cython coroutine, so creating the _get_sync_patched in wiring.py that calls _cwiring's _sync_inject, which effectively conserves behavior when running wiring.

martlaf avatar Feb 28 '23 23:02 martlaf

@rmk135 Would it be possible to release a fix for this bug in an upcoming release?

sgenya avatar Apr 09 '23 11:04 sgenya

Any updates?

yakimka avatar Aug 28 '23 14:08 yakimka

Any updates? I have same issue, For now I just using dependency-injector==4.38.0

Astral1020 avatar Nov 03 '23 02:11 Astral1020

I have a similar issue. Is there a workaround?

tsdaemon avatar Dec 27 '23 15:12 tsdaemon