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

Mypy fails type-check when using Generic["Something"] instead of Generic[Something] #17584

Closed
nerodono opened this issue Jul 25, 2024 · 2 comments
Labels
bug mypy got something wrong

Comments

@nerodono
Copy link

Bug Report

To Reproduce

import typing as t

if t.TYPE_CHECKING:
    Something = t.TypeVar("Something")

class Xxx(t.Generic['Something']):
    ...

def lol(x: Xxx[int]) -> None:
    ...

Expected Behavior

Same as the following code (which is passes the type-check):

import typing as t

if t.TYPE_CHECKING: # to not fail in runtime this should be removed too, however, I wanted to show that minimal changes affect the result
    Something = t.TypeVar("Something")

class Xxx(t.Generic[Something]):
    ...

def lol(x: Xxx[int]) -> None:
    ...

Actual Behavior

main.py:6: error: Free type variable expected in Generic[...]  [misc]
main.py:9: error: "Xxx" expects no type arguments, but 1 given  [type-arg]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.11.0 (compiled: yes)
  • Mypy command-line flags: default
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.10
@nerodono nerodono added the bug mypy got something wrong label Jul 25, 2024
@hauntsaninja
Copy link
Collaborator

class Xxx(t.Generic['Something']): <-- this will fail at runtime, so I think mypy is right to complain here.

>>> import typing
>>> class X(typing.Generic["asdf"]): ...
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/shantanu/.pyenv/versions/3.12.2/lib/python3.12/typing.py", line 384, in inner
    return func(*args, **kwds)
           ^^^^^^^^^^^^^^^^^^^
  File "/Users/shantanu/.pyenv/versions/3.12.2/lib/python3.12/typing.py", line 1054, in _generic_class_getitem
    raise TypeError(
TypeError: Parameters to Generic[...] must all be type variables or parameter specification variables.

@hauntsaninja hauntsaninja closed this as not planned Won't fix, can't repro, duplicate, stale Jul 27, 2024
@nerodono
Copy link
Author

nerodono commented Jul 27, 2024

so I think mypy is right to complain here.

Hmmm, sure, you're right. I haven't checked the runtime behavior. Seems like I haven't encountered crashes because I did that inside the ".pyi" file which is never executed.
Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

2 participants