| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
"""Example of basic FrozenConfigDict usage. |
| 16 |
|
| 17 |
This example shows the most basic usage of FrozenConfigDict, highlighting |
| 18 |
the differences between FrozenConfigDict and ConfigDict and including |
| 19 |
converting between the two. |
| 20 |
""" |
| 21 |
|
| 22 |
from absl import app |
| 23 |
from ml_collections import config_dict |
| 24 |
|
| 25 |
|
| 26 |
def print_section(name): |
| 27 |
print() |
| 28 |
print() |
| 29 |
print('-' * len(name)) |
| 30 |
print(name.upper()) |
| 31 |
print('-' * len(name)) |
| 32 |
print() |
| 33 |
|
| 34 |
|
| 35 |
def main(_): |
| 36 |
print_section('Attribute Types.') |
| 37 |
cfg = config_dict.ConfigDict() |
| 38 |
cfg.int = 1 |
| 39 |
cfg.list = [1, 2, 3] |
| 40 |
cfg.tuple = (1, 2, 3) |
| 41 |
cfg.set = {1, 2, 3} |
| 42 |
cfg.frozenset = frozenset({1, 2, 3}) |
| 43 |
cfg.dict = { |
| 44 |
'nested_int': 4, |
| 45 |
'nested_list': [4, 5, 6], |
| 46 |
'nested_tuple': ([4], 5, 6), |
| 47 |
} |
| 48 |
|
| 49 |
print('Types of cfg fields:') |
| 50 |
print('list: ', type(cfg.list)) |
| 51 |
print('set: ', type(cfg.set)) |
| 52 |
print('nested_list: ', type(cfg.dict.nested_list)) |
| 53 |
print('nested_tuple[0]: ', type(cfg.dict.nested_tuple[0])) |
| 54 |
|
| 55 |
frozen_cfg = config_dict.FrozenConfigDict(cfg) |
| 56 |
print('\nTypes of FrozenConfigDict(cfg) fields:') |
| 57 |
print('list: ', type(frozen_cfg.list)) |
| 58 |
print('set: ', type(frozen_cfg.set)) |
| 59 |
print('nested_list: ', type(frozen_cfg.dict.nested_list)) |
| 60 |
print('nested_tuple[0]: ', type(frozen_cfg.dict.nested_tuple[0])) |
| 61 |
|
| 62 |
cfg_from_frozen = config_dict.ConfigDict(frozen_cfg) |
| 63 |
print('\nTypes of ConfigDict(FrozenConfigDict(cfg)) fields:') |
| 64 |
print('list: ', type(cfg_from_frozen.list)) |
| 65 |
print('set: ', type(cfg_from_frozen.set)) |
| 66 |
print('nested_list: ', type(cfg_from_frozen.dict.nested_list)) |
| 67 |
print('nested_tuple[0]: ', type(cfg_from_frozen.dict.nested_tuple[0])) |
| 68 |
|
| 69 |
print('\nCan use FrozenConfigDict.as_configdict() to convert to ConfigDict:') |
| 70 |
print(cfg_from_frozen == frozen_cfg.as_configdict()) |
| 71 |
|
| 72 |
print_section('Immutability.') |
| 73 |
try: |
| 74 |
frozen_cfg.new_field = 1 |
| 75 |
except AttributeError as e: |
| 76 |
print(e) |
| 77 |
|
| 78 |
print_section('"==" and eq_as_configdict().') |
| 79 |
|
| 80 |
print(frozen_cfg == cfg) |
| 81 |
|
| 82 |
|
| 83 |
print(frozen_cfg.eq_as_configdict(cfg)) |
| 84 |
|
| 85 |
print(cfg.eq_as_configdict(frozen_cfg)) |
| 86 |
|
| 87 |
|
| 88 |
if __name__ == '__main__': |
| 89 |
app.run(main) |