omry / omegaconf

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

Feature: Read-only flag on leaf field #801

Open tarepan opened 3 years ago

tarepan commented 3 years ago

Summary

Request a feature which enable Read-only flag on leaf field in addition to whole conf and containers.
This solve the problem that interpolation field can be accidentally overridden.

Problem

Current limitation

Now we have Read-only flag feature.
This feature protect whole config or dict/container in config as below.

from omegaconf import OmegaConf

conf = OmegaConf.create("""
leaf_1: hello
nest_a:
  leaf_2: world
  leaf_3: ${leaf_1}
""")

OmegaConf.set_readonly(conf, True)
# or
OmegaConf.set_readonly(conf.nest_a, True)

conf.nest_a.leaf_3 = "overridden"
# ReadonlyConfigError: Cannot change read-only config container

But it cannot protect individual leaf nodes as bellow.

OmegaConf.set_readonly(conf.nest_a.leaf_2, True)
# AttributeError: 'str' object has no attribute '_set_flag'

Subsequent problem

This cause the problem that interpolation field can be accidentally overridden.
We hope to always sync conf.nest_a.leaf_3 with conf.leaf_1 in above example.
But value reassignment (e.g. conf.nest_a.leaf_3 = "overridden") easily break this sync.
What we can do is carefully reassign and merge...

Solution

Extend OmegaConf.set_readonly to accept leaf field.

API example:

OmegaConf.set_readonly((CONTAINER, FIELD_PATH_STR), Boolean)

# example
OmegaConf.set_readonly((conf, "nest_a.leaf_3"), True)

I do not know internal implementations of omegaconf, so this is just API example.
This enable leaf field protection, this results in safer configuration.

Jasha10 commented 3 years ago

Hello @tarepan, thank you for the feature request! I think that this is a reasonable idea. We will look into adding an API for setting leaf-nodes as readonly.