python / python/cpython

dataclass tries to generate `__init__()` even though the class already defines one

Aberta
#148,941 6 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

pending stdlib topic-dataclasses type-bug
Linguagem predominante
Python
Estrelas
77.2k
Forks
35.9k
Métricas de merge de PRs
Métricas de PR pendentes

Descrição

Bug report

Bug description:

When running this code:

from dataclasses import dataclass

@dataclass
class A:
    a: int = 1

@dataclass
class B(A):
    b: int
    def __init__(self, *args, **kwargs): ...

I got TypeError: non-default argument 'b' follows default argument

However, if I set init=False for the second dataclass, like this:

from dataclasses import dataclass

@dataclass
class A:
    a: int = 1

@dataclass(init=False)
class B(A):
    b: int
    def __init__(self, *args, **kwargs): ...

There error disappeared.

I think the error comes from the process where dataclass tries to generate the default __init__() and checks the fields. But, if I understand correctly, this should not happen when the class already defines its own __init__().

Although I'm not sure whether the behavior should be defined as a bug, I do find the results inconsistant with the docs, which says

If the class already defines __init__(), this parameter (init) is ignored.

so, intuitively, adding init=False shouldn't have changed the result.

CPython versions tested on:

3.12, 3.13, 3.14

Operating systems tested on:

Windows

Linked PRs
  • gh-151184
  • gh-153601

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Reproduza os dois exemplos usando dataclasses.dataclass e, em seguida, inspecione o trabalho relacionado em gh-151184 e gh-153601 antes de decidir se o comportamento ou a documentação é inconsistente. Considera-se concluído quando o tratamento pretendido de um init existente estiver estabelecido e coberto por evidências de regressão apropriadas.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
python
Domínio
backend
Tipo de issue
Bug
Dificuldade
4/5
Tempo estimado
3-5 dias
Status de atividade
Estagnada
Clareza
Razoavelmente clara
Facilidade para iniciantes
25/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.