python / python/mypy

Inconsistent "Invalid Metaclass" error for classes defined within functions

Open
#15,027 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-metaclasses topic-type-alias
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When a class:

  • is defined inside a function, and
  • uses a metaclass

then it mypy will inconsistently give an Invalid metaclass error based on whether the metaclass is specified via an alias name, or the original name from when the class is defined. This behaviour occurs regardless of whether the metaclass is defined inside or outside of the function. I would have expected no error.

To Reproduce

See on mypy playground

class M(type):
    pass


def f() -> None:
    _M = M

    class C(metaclass=_M): # Error
        pass
    
    class D(metaclass=M): # OK
        pass

Actual Behavior

main.py:8: error: Invalid metaclass "_M"  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.1.1
  • Python version used: 3.11

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 with the linked mypy playground and the nested-function reproduction, comparing the aliased metaclass _M with the original name M. Trace the invalid-metaclass check and confirm that equivalent aliases no longer produce inconsistent diagnostics while the example reports no error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.