2

I'm attempting to build a simple data-class example for YAML parsing which consists of recursive types.

The YAML in question looks like this:

---
folders:
  - name: a
    children:
      - name: b
  - name: c
    children: []

The way I am defining my types is like so:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from __future__ import annotations  # I'm on Python 3.9
from dataclass_wizard import YAMLWizard, LoadMeta
from dataclasses import dataclass


@dataclass
class DemoManifest(YAMLWizard):
    folders: List[DemoFolder]


@dataclass
class DemoFolder(YAMLWizard):
    name: str
    children: List[DemoFolder]


def main():
    LoadMeta(recursive=True).bind_to(DemoFolder)
    manifest = DemoManifest.from_yaml_file("recurse.yml")
    print(manifest)

It's a pretty simple example. I have one outer type which defines a list of DemoFolder objects, which potentially have a list of children of DemoFolder types as well.

When I run this, I get a RecursionError, maximum depth exceeded. Clearly somehow recursion is breaking the parsing. I thought that I solved the issue using the meta above, but it is definitely not working.

Is it possible to do self-referential deserialization in YAML for dataclass-wizard?


EDIT: This is not an issue of Python compiling. The code compiles and runs, it seems to be an issue with dataclass-wizard, which is where the recursion occurs.

Naftuli Kay
  • 87,710
  • 93
  • 269
  • 411
  • This is not an issue of Python compiling, the future `annotations` trick works and it's fine. It's specifically in the dataclass-wizard library that the problem emerges here when trying to deserialize a self-referential class. – Naftuli Kay Jun 09 '22 at 01:16
  • 1
    Hi there! I just saw this post and I thought it illustrated a common problem. I'm actually working through other issues in the linked project now (most noticeably with the `Generic` types) but def I'd be interested in supporting recursive references to dataclasses at some point. I feel like I have a general idea of how to accomplish it, but i'd just need to sit down and put it down on paper. Btw I am well aware of this error in particular, I just have not gotten around to opening an issue on it yet. – rv.kvetch Jun 09 '22 at 01:20
  • 1
    @rv.kvetch thank you so much for your response, I'll try to find another way around my particular problem. – Naftuli Kay Jun 09 '22 at 01:23
  • No problem! also don't hesitate to open an issue on the project repo in the meantime, however I definitely think recursive types is an important goal for the library to support. Btw one other thing I can point out is that the `recursive=True` only means the Meta config is applied recursively to nested classes, so again probably it is not what you are looking for in this case. – rv.kvetch Jun 09 '22 at 01:27
  • The recommended extension for files containing YAML documents has been `.yaml` since at least September *2006*. – Anthon Jun 09 '22 at 09:17

0 Answers0