Skip to content

Support overriding via args & kwargs #78

@xelandernt

Description

@xelandernt

Currently, it is possible to override injected arguments by provider overriding.
This makes sense, especially when testing, however it would be convenient to be able to override injection by passing the arguments to the function explicitly:

async def my_resource():
    return "resource"

class MyContainer(BaseContainer):
    config = providers.AsyncFactory(my_resource)
    
@inject
async def my_function(provided: str  = Provide[MyContainer.config]):
    print(provided)
    
async def run():
    await my_function()  # resource
    
    # RuntimeError: Injected arguments must not be redefined, field_name='provided'
    await my_function(provided="overriden")  # expected: overriden
    
    # TypeError: my_function() got multiple values for argument 'provided'
    await my_function("overriden")  # expected: overriden

Specific use case:
Sometimes I want to call a function that has dependency injection, but I want to override 1 or more parameters depending on context. I could use Container.my_provider.override() or similar, but that leads to additional code & doesn't work as well in an async context.

Is there perhaps another reason that this is currently not supported?

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions