Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda