Skip to content

Comments

Add explicit param injection#75

Closed
s3i7h wants to merge 4 commits intoivankorobkov:masterfrom
s3i7h:add_explicit_param_injection
Closed

Add explicit param injection#75
s3i7h wants to merge 4 commits intoivankorobkov:masterfrom
s3i7h:add_explicit_param_injection

Conversation

@s3i7h
Copy link

@s3i7h s3i7h commented Jan 21, 2021

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
Copy link
Owner

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
Copy link
Owner

Hi!

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

@s3i7h
Copy link
Author

s3i7h commented Feb 2, 2021

No worries! Take your time😊

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants