Get a bound method for cls.meth reference with injector

Sometimes I want to reference a class + method in some setup code but really use bound method of an instance. This is quite easy to do with Injector:

import injector
from dataclasses import dataclass

class BoundMethodProvider:
    _container: injector.Injector

    def __call__(self, meth):
        class_name = meth.__qualname__.rsplit('.', 1)[0]
        interface = meth.__globals__[class_name]
        instance = self._container.get(interface)
        method_name = meth.__name__
        return getattr(instance, method_name)

container = injector.Injector()
provider = container.get(BoundMethodProvider)
bar = provider(

Container will get you and instance of an interface with all it’s dependencies provided. Cool.

Leave a Reply

Back to Top