omegaconf icon indicating copy to clipboard operation
omegaconf copied to clipboard

`SCMode.INSTANTIATE` for attrs classes breaks when an attribute name has a leading underscore

Open bzczb opened this issue 2 years ago • 2 comments

Describe the bug According to the attrs API reference, attribute names are stripped of leading underscores in the __init__(): different behavior to dataclasses. But this quirk isn't handled by OmegaConf when instantiating the class.

To Reproduce

import attr
from omegaconf import OmegaConf, SCMode

@attr.s
class Foo():
    _bar: int = attr.ib(default=0)

OmegaConf.to_container(OmegaConf.structured(Foo), structured_config_mode=SCMode.INSTANTIATE)

Result

omegaconf.errors.ConfigTypeError: Could not create instance of `Foo`: Foo.__init__() got an unexpected keyword argument '_bar'
    full_key: 
    object_type=Foo

Expected result

Foo(_bar=0)

Workaround Set an alias in attr.ib(...) to the actual attribute name.

    _bar: int = attr.ib(default=0, alias='_bar')

Additional context

  • OmegaConf version: 2.3.0
  • Python version: 3.10.10
  • Operating system: Windows 10

bzczb avatar Apr 03 '23 06:04 bzczb

Thanks for the report, @bzczb. I can reproduce the error as well as the workaround.

Jasha10 avatar Apr 14 '23 22:04 Jasha10

@bzczb, patch welcome (along with a unit test).

omry avatar Apr 15 '23 19:04 omry