Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OmegaConf.to_object handling of init=False fields #879

Merged
merged 2 commits into from
Mar 29, 2022

Conversation

Jasha10
Copy link
Collaborator

@Jasha10 Jasha10 commented Mar 24, 2022

This PR improves OmegaConf.to_object so that structured configs with init=False fields can be handled.

This comes up for example when calling to_object on a structured config generated by hydra_zen.builds (as such structured configs use an init=False field for the _target_ key).

Here is a demo of the use-cases enabled by this PR:

# example.py
from dataclasses import dataclass, field
from omegaconf import DictConfig, OmegaConf

@dataclass
class Foo:
    x: str = field(init=False)
    y: str = field(init=False, default="default")
    z: str = field(init=False)
    def __post_init__(self) -> None:
        self.z = "set_by_post_init"


cfg1 = OmegaConf.structured(Foo)
assert OmegaConf.is_missing(cfg1, "x")
assert cfg1.y == "default"
assert OmegaConf.is_missing(cfg1, "z")

obj1 = OmegaConf.to_object(cfg1)
assert not hasattr(obj1, "x")
assert obj1.y == "default"
assert obj1.z == "set_by_post_init"


cfg2 = OmegaConf.structured(Foo)
cfg2.x = "new_x"
cfg2.y = "new_y"
cfg2.z = "new_z"

obj2 = OmegaConf.to_object(cfg2)
assert obj2.x == "new_x"
assert obj2.y == "new_y"
assert obj2.z == "new_z"

Pre-PR behavior:

$ python example.py
Traceback (most recent call last):
  File "/home/rig1/dev/omegaconf/example.py", line 22, in <module>
    obj1 = OmegaConf.to_object(cfg1)
...
omegaconf.errors.MissingMandatoryValue: Structured config of type `Foo` has missing mandatory value: x
    full_key: x
    object_type=Foo

Post-PR behavior:

$ python example.py  # no errors, assertions succeed

Closes #789.

@Jasha10 Jasha10 changed the title OmegaConf.to_object handling of init=False fields OmegaConf.to_object handling of init=False fields Mar 24, 2022
Copy link
Collaborator

@pixelb pixelb left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good. thanks!

@Jasha10 Jasha10 merged commit d2f0d46 into omry:master Mar 29, 2022
@Jasha10 Jasha10 deleted the closes789-init-false-to_object branch March 29, 2022 11:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Structured configs do not respect dataclasses.field(init=False)
2 participants