| 1 | # Copyright 2024 The ML Collections Authors. |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | """Example of ConfigDict usage of lock. |
| 16 | |
| 17 | This example shows the roles and scopes of ConfigDict's lock(). |
| 18 | """ |
| 19 | |
| 20 | from absl import app |
| 21 | from ml_collections import config_dict |
| 22 | |
| 23 | |
| 24 | def main(_): |
| 25 | cfg = config_dict.ConfigDict() |
| 26 | cfg.integer_field = 123 |
| 27 | |
| 28 | # Locking prohibits the addition and deletion of new fields but allows |
| 29 | # modification of existing values. Locking happens automatically during |
| 30 | # loading through flags. |
| 31 | cfg.lock() |
| 32 | try: |
| 33 | cfg.intagar_field = 124 # Raises AttributeError and suggests valid field. |
| 34 | except AttributeError as e: |
| 35 | print(e) |
| 36 | cfg.integer_field = -123 # Works fine. |
| 37 | |
| 38 | with cfg.unlocked(): |
| 39 | cfg.intagar_field = 1555 # Works fine too. |
| 40 | |
| 41 | print(cfg) |
| 42 | |
| 43 | |
| 44 | if __name__ == '__main__': |
| 45 | app.run() |