Mityuha / fresh-bakery

Bake dependency injections asynchronously and stupidly simple
https://fresh-bakery.readthedocs.io/en/latest/
MIT License
21 stars 0 forks source link

call-overload if a class has enter and call methods #55

Open ggurdanikita opened 1 month ago

ggurdanikita commented 1 month ago

mypy - 1.12.0 fresh-bakery - 0.4.2

mypy assumes that after calling two Cakes, the result will be the type returned by the call function, not enter as it actually happens.

For example:

import asyncio
import typing
from bakery import Bakery, Cake

class Cat:
    def __init__(self, name: str):
        self.name = name

    def __str__(self):
        return f"My name is {self.name}, i am a {self.__class__.__name__}"

class AnimalInterface(typing.Protocol):
    def __init__(self, name: str): ...

    def __str__(self): ...

class AnimalFactory:
    def __init__(self):
        print("DEBUG: AnimalFactory.__init__")

    def __call__(self, animal: type[AnimalInterface], name: str) -> AnimalInterface:
        print(f"DEBUG: AnimalFactory.__call__:  Animal name is {name = }, {animal = }")
        return animal(name)

    def __enter__(self) -> typing.Self:
        print("DEBUG: AnimalFactory.__enter__")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("DEBUG: AnimalFactory.__exit__")

class TestContainer(Bakery):
    animal_factory: AnimalFactory = Cake(
        Cake(
            AnimalFactory,
            animal=Cat,
            name="Ramon",
        )
    )

async def main() -> None:
    with AnimalFactory() as factory:
        my_animal = factory(Cat, "Ramon")
        print(my_animal)

if __name__ == "__main__":
    asyncio.run(main())

mypy error:

test.py:38: error: No overload variant of "Cake" matches argument types "type[AnimalFactory]", "type[Cat]", "str"  [call-overload]
test.py:38: note: Possible overload variants:
test.py:38: note:     def [T] Cake(recipe: Awaitable[T]) -> T
test.py:38: note:     def [T] Cake(recipe: AsyncContextManager[T]) -> T
test.py:38: note:     def [T] Cake(recipe: ContextManager[T]) -> T
test.py:38: note:     def [P`-1, T] Cake(recipe: Callable[P, Awaitable[T]], *recipe_args: P.args, **recipe_kwargs: P.kwargs) -> T
test.py:38: note:     def [P`-1, T] Cake(recipe: Callable[P, T], *recipe_args: P.args, **recipe_kwargs: P.kwargs) -> T
test.py:38: note:     def [T] Cake(recipe: T) -> T
Found 1 error in 1 file (checked 1 source file)
Mityuha commented 1 month ago

@ggurdanikita Thank you for issue reporting. It seems as mypy 1.12.0 regression for me. So I opened a new issue in mypy project. Let's follow this issue