Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for recursive data? #287

Closed
masinc opened this issue Nov 30, 2022 · 3 comments · Fixed by #290
Closed

Support for recursive data? #287

masinc opened this issue Nov 30, 2022 · 3 comments · Fixed by #290

Comments

@masinc
Copy link

masinc commented Nov 30, 2022

Python: 3.10.8
pyserde: 0.9.5

I defined the following class and an error occurred.

from dataclasses import dataclass
from serde import serde, field
from typing import Optional

@dataclass
class A:
    a: Optional['A'] # = field(skip_if_false=True)

# RecursionError
A = serde(A)

The field value is commented out, but a RecurtionError is raised in both case.

Rust Serde worked with similar recursive data structures.

use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct A {
    a: Option<Box<A>>,
}
@yukinarit
Copy link
Owner

Hi @masinc, This is only the workaround I could come up with

from dataclasses import dataclass
from serde import serde, to_dict, from_dict
from typing import Optional
from typing import Generic, TypeVar

T = TypeVar('T')

@serde
@dataclass
class A(Generic[T]):
    a: Optional[T]

a = A(A(A(None)))
print(to_dict(a))
print(from_dict(A[A[A[int]]], {'a': {'a': {'a': None}}}))  # int in A[A[A[int]]] is a fake type

Output

{'a': {'a': {'a': None}}}
A(a=A(a=A(a=None)))

@masinc
Copy link
Author

masinc commented Dec 1, 2022

Thx @yukinarit.
Adding a custom deserializer field gave the expected behavior!

@yukinarit
Copy link
Owner

Published pyserde v0.9.6!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants