ivankorobkov / python-inject

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

Add explicit param injection #75

Open s3i7h opened 3 years ago

s3i7h commented 3 years ago

Thank you for bringing this awesome project to life!

I was working on a project and came up to this kind of code where a_setting and b_setting control the parameters of some_injectable_function:

import inject

@inject.params(a=10, b=20, c=30)
def some_injectable_function(a, b, c):
    ...

def some_function(a_setting=True, b_setting=False):
    if a_setting and b_setting:
        result = some_injectable_function(a=1, b=1, c=1)
    elif a_setting:
        result = some_injectable_function(a=1, c=1)
    elif b_setting:
        result = some_injectable_function(b=1)
    else:
        result = some_injectable_function()

...but I thought this will get more complex and uneasy to read if there's more conditions and parameters. I think this problem comes from not having ways to explicitly set a parameter to be injected.

I implemented a MARKER object that the injector will detect and replaces with the injected value. With this PR, you would be able to write it like

import inject

@inject.params(a=10, b=20, c=30)
def some_injectable_function(a, b, c):
    ...

def some_function(a_setting=True, b_setting=False):
    result = some_injectable_function(
        a=1 if a_setting else inject.MARKER,
        b=1 if b_setting else inject.MARKER,
        c=1 if a_setting else inject.MARKER,
    )

or

import inject

@inject.params(a=10, b=20, c=30)
def some_injectable_function(a, b, c):
    ...

def some_function(a_setting=True, b_setting=False):
    a = b = c = inject.MARKER
    if a_setting:
        a = c = 1
    if b_setting:
        b = 1
    result = some_injectable_function(a, b, c)

Comments well appreciated! Please tell me if there's any flaw in my code.

ivankorobkov commented 3 years ago

Hi!

Thank you for a pull request. Unfortunately, I'm a little busy right now. I'll try to take a look at the weekend.

ivankorobkov commented 3 years ago

Hi!

I did not forget about you pull request, but I'm still a little busy right now.

s3i7h commented 3 years ago

No worries! Take your time😊