Skip to content

Implement a way to specify typevar of Selector #930

@leonarduschen

Description

@leonarduschen

Background

My usual usecase of Selector is when I have an interface with multiple implementations:

class Animal:
    def __init__(self) -> None:
        pass


class Dog(Animal):
    pass


class Cat(Animal):
    pass

And then the container:

class Container(containers.DeclarativeContainer):
    get_dog = providers.Singleton(Dog)
    get_cat = providers.Singleton(Cat)
    get_animal = providers.Selector(lambda: random.choice(["cat", "dog"]), cat=get_cat, dog=get_dog)

Usage:

def main() -> None:
    container = Container()

    animal = container.get_animal()
    reveal_type(animal)  # Revealed type is Any

Desired behaviors

Ideally, Selector should:

  1. Allow users to specify type: get_animal = providers.Selector[Animal](lambda: random.choice(["cat", "dog"]), cat=get_cat, dog=get_dog)
  2. Automatically infer from the kwargs of providers: cat and dog are both animals, so get_animal is Selector[Animal]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions