omry / omegaconf

Flexible Python configuration system. The last one you will ever need.
BSD 3-Clause "New" or "Revised" License
1.99k stars 115 forks source link

ValidationError for forward references inside a container #1174

Open D-Sokol opened 7 months ago

D-Sokol commented 7 months ago

Describe the bug I have a dataclass config and want to convert it into a YAML representation via OmegaConf, but it raises a ValidationError since I use forward reference in the list. Here is the simplified version of my code:

from dataclasses import dataclass
from omegaconf import OmegaConf
from typing import Optional

@dataclass
class Tree:
    value: int = -1
    children: Optional[list["Tree"]] = None

mytree = Tree(value=1, children=[Tree(value=2)])

config = OmegaConf.structured(mytree)
print(config)

Expected behavior Output {'value': 1, 'children': [{'value': 2, 'children': None}]}, no error

Actual behavior

omegaconf.errors.ValidationError: Unsupported value type: 'ForwardRef('Tree')'
    full_key: children
    object_type=None

I believe this is a bug since the following very similar code produces an expected result:

@dataclass
class Tree:
    value: int = -1
    child: Optional["Tree"] = None

mytree = Tree(value=1, child=Tree(value=2))

config = OmegaConf.structured(mytree)
print(config)
# {'value': 1, 'child': {'value': 2, 'child': None}}

Additional context