python / python/mypy

Incorrect number of arguments expected when dataclass is applied using __init_subclass__

Open
#11,056 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature priority-2-low topic-dataclasses
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

A bit obscure and perhaps not a supported pattern, but using __init_subclass__ to turn subclasses into dataclasses in order to remove the need for library users to use the @dataclass decorator makes mypy confused about how many args the subclass' constructor expects.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.10&gist=d5900693474f425fc04dc5d36bd0eb2d

from dataclasses import dataclass


class Event:
    def __init_subclass__(cls):
        dataclass(cls)


class BaseEvent(Event):
    base_field: str


class SubEvent(BaseEvent):
    sub_field: str
    
    
SubEvent("base", "sub")

Expected Behavior

No errors from mypy.

Actual Behavior

In [1]: from dataclasses import dataclass
    ..: 
    ..: 
    ..: class Event:
    ..:     def __init_subclass__(cls):
    ..:         dataclass(cls)
    ..: 
    ..: 
    ..: class BaseEvent(Event):
    ..:     base_field: str
    ..: 
    ..: 
    ..: class SubEvent(BaseEvent):
    ..:     sub_field: str
    ..: 
    ..: 
    ..: SubEvent("base", "sub")
    ..: 
Out[1]: SubEvent(base_field='base', sub_field='sub')
main.py:17: error: Too many arguments for "SubEvent"
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10
  • Operating system and version: n/a (playground)

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-play reproducer and compare how mypy handles dataclasses applied in init_subclass with ordinary @dataclass usage. Trace the constructor-argument inference for BaseEvent and SubEvent, then verify that mypy accepts SubEvent("base", "sub") without errors.

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.