python / python/mypy

PEP-681 - Inheriting class doesn't recognize kw_only=True from parent class

Open
#17,375 1 comment 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

A class inheriting a class with kw_only=True and using a dataclass_transform doesn't recognize kw_only being set, even though in runtime it does not yield an error. Originally found in sqlalchemy's usage (https://github.com/sqlalchemy/sqlalchemy/issues/11485)

To Reproduce

from typing import Optional, Any
import typing_extensions


def field(default: Any=None, init: bool=True, repr: bool=True) -> Any:
    pass

@typing_extensions.dataclass_transform(
    field_specifiers=(
        field,
    )
)
class ModelMeta(type):
    pass

class ModelBase(metaclass=ModelMeta):
    def __init_subclass__(cls, kw_only: bool=False) -> None:
        pass

class Base(ModelBase, kw_only=True):
    pass

class Vehicle(Base):
    b: Optional[str] = field(default=None)
    c: int

Expected Behavior

No error.

Actual Behavior

error: Attributes without a default cannot follow attributes with one  [misc]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.10
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12

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 minimal Python reproducer in the issue and trace mypy's PEP 681 dataclass_transform handling for inherited kw_only settings. Compare the reported ordering error with the expected behavior, then add a regression test for this reproducer and run the relevant test suite to confirm that no error is reported.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
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.