python / python/mypy

Mypy doesn't detect new metaclass on subclass

Open
#17,657 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

If you subclass a class with a metaclass but change the metaclass to your own with a different method signature, mypy does not pick up on that.

To Reproduce

Example:

from enum import EnumType, StrEnum as _StrEnum, auto

class EnumMeta(EnumType):
  def __call__(cls, value=None, **kwargs):
    # Return first enum if value is None
    if value is None:
      value = next(iter(cls))
    return super().__call__(value, **kwargs)


class StrEnum(_StrEnum, metaclass=EnumMeta):
  @staticmethod
  def _generate_next_value_(name, *args):
    # auto() defaults to name.lower()
    return name


class FingerprintSource(StrEnum):
  can = auto()
  fw = auto()
  fixed = auto()


FingerprintSource()

Out: <FingerprintSource.can: 'can'>

Expected Behavior

Mypy passes

Actual Behavior

selfdrive/car/data_structures.py:310: error: Missing positional argument "value" in call to "FingerprintSource"  [call-arg]

Your Environment

mypy 1.11.1 (compiled: yes)
Python 3.11.4

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 by running the supplied Python example with mypy 1.11.1 and confirming the false missing-argument error. Then trace how mypy determines the callable signature for FingerprintSource when its subclass declares EnumMeta; add focused coverage for this case and verify that the example type-checks without the 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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.