SmartDict: Dynamic pointing of values in Python dictionaries
Introduction
Chain assignment of dictionary values, which can be used to reduce redundancy in configuration dictionaries.
Installation
1 | pip install smartdict |
Usage
Assuming the following configuration dictionary exists:
1 | { |
It can be observed that many paths such as train_path
are related to the dataset name dataset, and the store storage path is related to the dataset name, network structure, and so on. Additionally, if the dataset or network structure is changed, the configuration dictionary needs to be modified complexly.
One solution is to handle the redundant information in Python code. For example, the value of train_path
is directly assigned to train, in the code as follows:
1 | data['load']['train_path'] = os.path.join('~', 'data', data['dataset'], data['load']['train_path']) |
However, this method is not flexible enough. As the number of configuration properties increases, the amount of code required also increases linearly, making the preprocessing of configuration data slightly cumbersome.
Normal String Referencing ${}
We propose to construct the dictionary values as dynamic data, for example:
1 | { |
The value of train_path
is dynamically constructed by referencing the value of base_path
and train
, and the value of store
is dynamically constructed by referencing the value of dataset
, network.num_hidden_layers
, and network.num_attention_heads
.
The above configuration dictionary can be processed as follows:
1 | # solution 1 |
Highly recommended to use smartdict
along with Oba:
1 | from oba import Obj |
Full Match Referencing ${}$
In the Normal String Referencing ${}
solution, the value of the configuration dictionary is a string. The reference is performed through a chain path (separated by .
) within the ${}
identifier.
The Full Match Reference only allows the property value to be completely covered by the identifier ${}$
. For example:
1 | import oba |
In which b
is identical to c
through the Full Match Reference.
Summon Magic
Sometimes, we may wish to generate the path through timestamps or random numbers. We can first construct the following two classes:
TimestampMagic
1 | import datetime |
RandomMagic
1 | import random |
Then, we can use the following configuration dictionary:
1 | import smartdict |
The principle behind this is to override the class’s []
operator to make it behave the same as a dictionary or list.
License
MIT
Links
SmartDict: Dynamic pointing of values in Python dictionaries