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 2.1: changes in DictConfig __getitem__ and __getattr__ #515

Closed
omry opened this issue Feb 5, 2021 · 0 comments · Fixed by #516
Closed

OmegaConf 2.1: changes in DictConfig __getitem__ and __getattr__ #515

omry opened this issue Feb 5, 2021 · 0 comments · Fixed by #516
Milestone

Comments

@omry
Copy link
Owner

omry commented Feb 5, 2021

An historical decision was to make __getitem__ and __getattr__ return None if a the input key is not found.
This is inconsistent with the behavior of plain dict and regular Python objects.

Fixing this is a breaking change, users depending on it will need small code changes.

Accessing a non existing attribute

In general,

cfg.some_attribute
# and
cfg["some_attribute"]

Can be replaced with:

cfg.get("some_attribute")
# or
getattr(cfg, "some_attribute", None)

Depending on the type annotation of cfg, one may be more appropriate than the other, but both will work.

Checking if an attribute exists

If the context of your usage is is existence check, you can also use:

if cfg["some_attribute"] is not None:
   ...

And

if cfg.some_attribute is not None:
   ...

Will have to be replaced with

if "some_attribute" in cfg:
  ...

Note that is cfg is ducktyped as a type, you can use hasattr just like you would on an real instance of Config:

def foo(cfg: Config):
  # before
  if cfg.some_attribute is not None: 
    ..
  # after
  if hasattr(cfg, "some_attribute"):
    ...

Note:
DictConfig put into struct mode is already behaving in the new way (raising exceptions).
This change should not affect most Hydra users because Hydra puts the cfg object into struct mode by default.

@omry omry added this to the OmegaConf 2.1 milestone Feb 5, 2021
@omry omry changed the title DictConfig __getitem__ and __getattr__ are inconsistent with plain dict DictConfig __getitem__ and __getattr__ are inconsistent with plain dict and objects Feb 5, 2021
@odelalleau odelalleau reopened this Feb 5, 2021
@omry omry changed the title DictConfig __getitem__ and __getattr__ are inconsistent with plain dict and objects OmegaConf 2.1: changes in DictConfig __getitem__ and __getattr__ Feb 5, 2021
@omry omry closed this as completed in #516 Feb 5, 2021
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 a pull request may close this issue.

2 participants