python / python/mypy

stubtest: False-positive errors for `type[T]` attributes with non-`type` metaclasses

Open
#13,316 2 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-stubtest
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Given a stub like so:

from abc import ABCMeta
class Y(metaclass=ABCMeta): ...
class Z:
    foo: type[Y]

And a runtime like so:

from abc import ABCMeta
class Y(metaclass=ABCMeta): ...
class Z:
    foo = Y

Stubtest will issue the following complaint:

error: Z.foo variable differs from runtime type abc.ABCMeta

This error can be reproduced with any custom metaclass; it's not just ABCMeta that triggers the bug:

# STUB
class Meta(type): ...
class Y(metaclass=Meta): ...
class Z:
    foo: type[Y]

# RUNTIME:
class Meta(type): ...
class Y(metaclass=Meta): ...
class Z:
    foo = Y

To Reproduce

  1. Check out a local clone of mypy
  2. Activate a virtual environment with an editable install of mypy
  3. Apply this diff:
diff --git a/mypy/test/teststubtest.py b/mypy/test/teststubtest.py
index 2adbfaac2..60ddebc7f 100644
--- a/mypy/test/teststubtest.py
+++ b/mypy/test/teststubtest.py
@@ -208,6 +208,21 @@ class StubtestUnit(unittest.TestCase):
             """,
             error="X.mistyped_var",
         )
+        yield Case(
+            stub="""
+            class Meta(type): ...
+            class Y(metaclass=Meta): ...
+            class Z:
+                foo: type[Y]
+            """,
+            runtime="""
+            class Meta(type): ...
+            class Y(metaclass=Meta): ...
+            class Z:
+                foo = Y
+            """,
+            error=None
+        )
  1. Run pytest ./mypy/test/teststubtest.py

Expected Behavior

No error should be emitted.

Actual Behavior

An error was emitted.

Cc. @hauntsaninja

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start in mypy/test/teststubtest.py by adding and running the shown StubtestUnit case with pytest ./mypy/test/teststubtest.py. Trace the stubtest comparison exercised by that case, and consider the work complete when the custom-metaclass example emits no error while the existing tests still pass.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing-qa, tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.