Debian Codegraph @

ml_collections/config_dict/examples/config_dict_advanced.py

raw symbols SCIP
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.
16
17 This example includes loading a ConfigDict in FLAGS, locking it, type
18 safety, iteration over fields, checking for a particular field, unpacking with
19 `**`, and loading dictionary from string representation.
20 """
21
22 from absl import app
23 from ml_collections import config_flags
24 import yaml
25
26 _CONFIG = config_flags.DEFINE_config_file(
27 'my_config',
28 default='ml_collections/config_dict/examples/config.py')
29
30
31 def hello_function(string, **unused_kwargs):
32 return 'Hello {}'.format(string)
33
34
35 def print_section(name):
36 print()
37 print()
38 print('-' * len(name))
39 print(name.upper())
40 print('-' * len(name))
41 print()
42
43
44 def main(_):
45 # Config is already loaded in FLAGS.my_config due to the logic hidden
46 # in app.run().
47 config = _CONFIG.value
48
49 print_section('Printing config.')
50 print(config)
51
52 # Config is of our type ConfigDict.
53 print('Type of the config {}'.format(type(config)))
54
55 # By default it is locked, thus you cannot add new fields.
56 # This prevents you from misspelling your attribute name.
57 print_section('Locking.')
58 print('config.is_locked={}'.format(config.is_locked))
59 try:
60 config.object.new_field = -3
61 except AttributeError as e:
62 print(e)
63
64 # There is also "did you mean" feature!
65 try:
66 config.object.floet = -3.
67 except AttributeError as e:
68 print(e)
69
70 # However if you want to modify it you can always unlock.
71 print_section('Unlocking.')
72 with config.unlocked():
73 config.object.new_field = -3
74 print('config.object.new_field={}'.format(config.object.new_field))
75
76 # By default config is also type-safe, so you cannot change the type of any
77 # field.
78 print_section('Type safety.')
79 try:
80 config.float = 'jerry'
81 except TypeError as e:
82 print(e)
83 config.float = -1.2
84 print('config.float={}'.format(config.float))
85
86 # NoneType is ignored by type safety and can both override and be overridden.
87 config.float = None
88 config.float = -1.2
89
90 # You can temporarly turn type safety off.
91 with config.ignore_type():
92 config.float = 'tom'
93 print('config.float={}'.format(config.float))
94 config.float = 2.3
95 print('config.float={}'.format(config.float))
96
97 # You can use ConfigDict as a regular dict in many typical use-cases:
98 # Iteration over fields:
99 print_section('Iteration over fields.')
100 for field in config:
101 print('config has field "{}"'.format(field))
102
103 # Checking if it contains a particular field using the "in" command.
104 print_section('Checking for a particular field.')
105 for field in ('float', 'non_existing'):
106 if field in config:
107 print('"{}" is in config'.format(field))
108 else:
109 print('"{}" is not in config'.format(field))
110
111 # Using ** unrolling to pass the config to a function as named arguments.
112 print_section('Unpacking with **')
113 print(hello_function(**config))
114
115 # You can even load a dictionary (notice it is not ConfigDict anymore) from
116 # a yaml string representation of ConfigDict.
117 # Note: __repr__ (not __str__) is the recommended representation, as it
118 # preserves FieldReferences and placeholders.
119 print_section('Loading dictionary from string representation.')
120 dictionary = yaml.load(repr(config), yaml.UnsafeLoader)
121 print('dict["object_reference"]["dict"]["dict"]["float"]={}'.format(
122 dictionary['object_reference']['dict']['dict']['float']))
123
124
125 if __name__ == '__main__':
126 app.run(main)