Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
Create recursive dataclass with self-referential type hints

I want to write a dataclass definition in Python, but can't refer to that same class inside the declaration.

Mainly what I want to achieve is the typing of this nested structure, as illustrated below:

 @dataclass
 class Category:
     title: str
     children: [Category] # I can't refer to a "Category"
  
 tree = Category(title='title 1', children=[
     Category('title 11', children=[]),
     Category('title 12', children=[])
 ])
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Option #1

You can wrap class name in a string in order to forward-declare the annotation:

from dataclasses import dataclass
from typing import List


@dataclass
class Category:
    title: str
    children: List['Category']

Option #2

You can include a __future__ import so that all annotations by default are forward-declared as below. In this case, you can also eliminate the typing import and use new-style annotations in Python 3.7 and above.

from __future__ import annotations

from dataclasses import dataclass


@dataclass
class Category:
    title: str
    children: list[Category]
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda