omry / omegaconf

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

Add support for dataclasses._MISSING_TYPE #1136

Open majiayu000 opened 8 months ago

majiayu000 commented 8 months ago

Describe the bug

In Python version >= 3.11, dataclasses prohibits setting the default value to mutable objects

so this is often the case : common: Example = field(default_factory=Example)

Here, if no assignment is given, the object becomes a _MISSING_TYPE.

When using this type in OmegaConf.structured, an error will occur.

Just like this https://github.com/facebookresearch/fairseq/pull/5359#issuecomment-1779634288

To Reproduce

Run the code below will get this error

from dataclasses import dataclass, field
from typing import List, Any
from omegaconf import OmegaConf

@dataclass
class Example:
    num: int

@dataclass
class TestConfig(Example):
    common: Example = field(default_factory=Example)

for k, field_info in TestConfig.__dataclass_fields__.items():
    default_value = field_info.default
    default_factory = field_info.default_factory
    print(
        f"Field: {k}, Default Value: {default_value}, Default Factory: {default_factory}"
    )

    mis = OmegaConf.structured(default_factory)

image

Expected behavior

Maybe add a type judgement for better compatibility.

Additional context