Skip to content

feature request: explicity metaclass().__getitem__ typing #6313

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

Closed
Levitanus opened this issue Feb 4, 2019 · 5 comments
Closed

feature request: explicity metaclass().__getitem__ typing #6313

Levitanus opened this issue Feb 4, 2019 · 5 comments

Comments

@Levitanus
Copy link

Mypy does well with metaclass __getitem__ when the class is instatiated,
but in case of indexing just the child class, it fails:

class Other:
    ...

class GenMeta(type):
    def __getitem__(cls, ref: Type[int]) -> Type[Other]:
        return Other

class Gen(metaclass=GenMeta):
    ...

a = Gen[int]  # "Gen" expects no type arguments, but 1 given
reveal_type(a)  # Revealed type is 'Any'
b = Gen[int]()
reveal_type(b)  # Revealed type is 'pyksp.simple_test.Other'


def foo(arg: Gen[int]) -> None:  # "Gen" expects no type arguments, but 1 given
    reveal_type(arg)  # Revealed type is 'pyksp.simple_test.Gen'

I think it would be very useful to check, especially in case of function annotations

@ilevkivskyi
Copy link
Member

ilevkivskyi commented Feb 4, 2019

It is expected that it works in runtime context but doesn't work in type context, because anything that appears in type context should be known statically. Consider a simpler example:

def f() -> Type[int]: ...

x = f()()  # OK, inferred type for x is `int`
y: f()  # Fails

The error message however is confusing, but then this is essentially a duplicate of #4030

@ilevkivskyi
Copy link
Member

By the way, the workaround for your case is to use if TYPE_CHECKING: ....

@Levitanus
Copy link
Author

Sorry, can you expand the last comment?
If TYPE_CHECKING where?

@ilevkivskyi
Copy link
Member

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    <definition of Gen that would satisfy mypy>
else:
    <your definition that will be executed at runtime>

@A5rocks
Copy link
Collaborator

A5rocks commented Feb 17, 2023

If I understand the reason this can't happen correctly, wouldn't this be solved by a type that has an invariant rather than covariant (?) type variable?

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

3 participants