| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
"""Example of initialization features and gotchas in a ConfigDict. |
| 16 |
""" |
| 17 |
|
| 18 |
import copy |
| 19 |
|
| 20 |
from absl import app |
| 21 |
from ml_collections import config_dict |
| 22 |
|
| 23 |
|
| 24 |
def print_section(name): |
| 25 |
print() |
| 26 |
print() |
| 27 |
print('-' * len(name)) |
| 28 |
print(name.upper()) |
| 29 |
print('-' * len(name)) |
| 30 |
print() |
| 31 |
|
| 32 |
|
| 33 |
def main(_): |
| 34 |
|
| 35 |
inner_dict = {'list': [1, 2], 'tuple': (1, 2, [3, 4], (5, 6))} |
| 36 |
example_dict = { |
| 37 |
'string': 'tom', |
| 38 |
'int': 2, |
| 39 |
'list': [1, 2], |
| 40 |
'set': {1, 2}, |
| 41 |
'tuple': (1, 2), |
| 42 |
'ref': config_dict.FieldReference({'int': 0}), |
| 43 |
'inner_dict_1': inner_dict, |
| 44 |
'inner_dict_2': inner_dict |
| 45 |
} |
| 46 |
|
| 47 |
print_section('Initializing on dictionary.') |
| 48 |
|
| 49 |
example_cd = config_dict.ConfigDict(example_dict) |
| 50 |
|
| 51 |
|
| 52 |
print(type(example_cd.inner_dict_1)) |
| 53 |
|
| 54 |
|
| 55 |
print(id(example_cd.inner_dict_1) == id(example_cd.inner_dict_2)) |
| 56 |
|
| 57 |
print_section('Initializing on ConfigDict.') |
| 58 |
|
| 59 |
|
| 60 |
example_cd_cd = config_dict.ConfigDict(example_cd) |
| 61 |
|
| 62 |
|
| 63 |
print(example_cd == example_cd_cd) |
| 64 |
|
| 65 |
|
| 66 |
print(id(example_cd) == id(example_cd_cd)) |
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
list_to_ids = lambda x: [id(element) for element in x] |
| 71 |
print( |
| 72 |
set(list_to_ids(list(example_cd.values()))) == set( |
| 73 |
list_to_ids(list(example_cd_cd.values())))) |
| 74 |
|
| 75 |
print_section('Initializing on self-referencing dictionary.') |
| 76 |
|
| 77 |
|
| 78 |
self_ref_dict = copy.deepcopy(example_dict) |
| 79 |
self_ref_dict['self'] = self_ref_dict |
| 80 |
self_ref_cd = config_dict.ConfigDict(self_ref_dict) |
| 81 |
|
| 82 |
|
| 83 |
print(id(self_ref_cd) == id(self_ref_cd.self)) |
| 84 |
|
| 85 |
print_section('Unexpected initialization behavior.') |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
dict_in_list_in_dict = {'list': [{'troublemaker': 0}]} |
| 90 |
dict_in_list_in_dict_cd = config_dict.ConfigDict(dict_in_list_in_dict) |
| 91 |
print(type(dict_in_list_in_dict_cd.list[0])) |
| 92 |
|
| 93 |
|
| 94 |
referred_dict = {'key': 'value'} |
| 95 |
bad_reference = {'referred_dict': referred_dict, 'list': [referred_dict]} |
| 96 |
bad_reference_cd = config_dict.ConfigDict(bad_reference) |
| 97 |
print(id(bad_reference_cd.referred_dict) == id(bad_reference_cd.list[0])) |
| 98 |
|
| 99 |
|
| 100 |
if __name__ == '__main__': |
| 101 |
app.run() |