omry / omegaconf

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

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

Closed bzczb closed 7 months ago

bzczb commented 1 year ago

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

Jasha10 commented 1 year ago

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

omry commented 1 year ago

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