omegaconf icon indicating copy to clipboard operation
omegaconf copied to clipboard

Please support Literal type annotation and string defaults in str Enum annotations

Open Saya47 opened this issue 9 months ago • 2 comments

Hello I like to use structured configs to have auto completion from the IDE but I have two issues:

First, Literal type annotation is not supported:

from dataclasses import dataclass
from typing import Literal
from omegaconf import OmegaConf


@dataclass
class MyConfig:
    mode: Literal["train", "test"] = "train"


conf = OmegaConf.structured(MyConfig)

Error:

ValidationError: Unexpected type annotation: Literal[train, test]
    full_key: mode
    object_type=MyConfig

Second issue is that if I use String Enum's, I cannot provide a string default for it anymore which is pretty annoying!


from dataclasses import dataclass
from typing import Literal
from omegaconf import OmegaConf
from enum import Enum


class Mode(str, Enum):
    Train = "train"
    Test = "test"


@dataclass
class MyConfig:
    mode: Mode = "train"


conf = OmegaConf.structured(MyConfig)

Error:

ValidationError: Invalid value 'train', expected one of [Train, Test]
    full_key: mode
    object_type=MyConfig

To alleviate this I would have to do mode: Mode = Mode("train")which is not very intuitive, so if I had Literal support I wouldn't even need to try Enums.

Thanks very much for this great library. It has helped me immensely.

Saya47 avatar Mar 26 '25 15:03 Saya47

The invalid value exception is correct, you should use Mode.Train, otherwise your typehint would be mode: Mode | str as the enum provides properties like name and value. I second literal support though

twsl avatar Jun 04 '25 09:06 twsl

This would be cool :)

EternalGoldenBraid avatar Aug 20 '25 11:08 EternalGoldenBraid