ivankorobkov / python-inject

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

Why i cannot inject Callable if functional style instead of class? #41

Closed vitalij23 closed 4 years ago

vitalij23 commented 4 years ago

.

vitalij23 commented 4 years ago

Why I cannot inject Callable in functional style instead of class?

vitalij23 commented 4 years ago

config

def my_config(binder): binder.bind_to_provider('dbfunc', lambda: realdbfunc)

usage

import inject db: callable = inject.attr('dbfunc') db()

not working:

@inject.autoparams('dbfunc') def a(dbfunc:callable): dbfunc()

ivankorobkov commented 4 years ago

Hi,

@inject.autoparams injection works on types as in dbfunc:callable. However, you bind your realdbfunc to a string dbfunc. You may try to switch it to:

binder.bind_to_provider(callable, lambda: ...)

But It don't think it will work either because keys must be hashable, and callable as far as I remember is not.

So, instead of autoparams use params:

binder.bind_to_provider('dbfunc', lambda: ...) # 'dbfunc' is a key.

@inject.params(dbfunc='dbfunc') # param name to a binder key.
def a(dbfunc):
  pass