Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to fix type errors? #102

Open
Spoonrad opened this issue May 8, 2024 · 2 comments
Open

How to fix type errors? #102

Spoonrad opened this issue May 8, 2024 · 2 comments

Comments

@Spoonrad
Copy link

Spoonrad commented May 8, 2024

How can I fix typing errors when using this library?

Example:

from abc import ABC, abstractmethod

import inject


class ICache(ABC):

    @abstractmethod
    def check(self) -> bool:
        ...

class Cache(ICache):
    ...

    def check(self) -> bool:
        return True

def test_inject() -> None:

    inject.configure(lambda binder: binder.bind(ICache, Cache()))  # type: ignore[arg-type]
    cache = inject.instance(ICache)
    cache.check()
mypy tests/test_inject.py
tests\test_inject.py:22: error: Item "object" of "object | Any" has no attribute "check"  [union-attr]

If I specify the type like this: cache: ICache I get an assignment error instead. How can I resolve this please?

@etsvetanov
Copy link

etsvetanov commented May 11, 2024

I don't think it's currently possible. I believe this happens because of the overloaded inject.instance()

Injectable = Union[object, Any]
# ....
@overload
def instance(cls: Hashable) -> Injectable: ...

And I suppose most things are considered "hashable":

In [1]: from abc import ABC, abstractmethod

In [2]: class ICache(ABC):
   ...:
   ...:     @abstractmethod
   ...:     def check(self) -> bool:
   ...:         ...
   ...:

In [3]: from collections.abc import Hashable

In [4]: issubclass(ICache, Hashable)
Out[4]: True

My understanding is that inject allows to bind to any "hashable" for convenience but maybe there should be a more specific type for binding to an arbitrary object/value?

@Spoonrad
Copy link
Author

Doesn't look too difficult to fix given how broad the type spec currently is. Something like this should work:

InjectableTypeVar = TypeVar("InjectableTypeVar")

@overload
def instance(cls: type[InjectableTypeVar]) -> InjectableTypeVar:
   ...

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

No branches or pull requests

2 participants