Let's say I have a (simplified) class as below. I am using it for a program configuration (hyperparameters).
# config.py
class Config(object): # default configuration
GPU_COUNT = 1
IMAGES_PER_GPU = 2
MAP = {1:2, 2:3}
def display(self):
pass
# experiment1.py
from config import Config as Default
class Config(Default): # some over-written configuration
GPU_COUNT = 2
NAME='2'
# run.py
from experiment1 import Config
cfg = Config()
...
cfg.NAME = 'ABC' # possible runtime over-writing
# Now I would like to save `cfg` at this moment
I'd like to save this configuration and restore later. The member functions must be out of concern when restoring.
1. When I tried pickle:
import pickle
with open('cfg.pk', 'rb') as f: cfg = pickle.load(f)
##--> AttributeError: Can't get attribute 'Config' on <module '__main__'>
I saw a solution using class_def of Config, but I wish I can restore the configuration without knowing the class definition (eg, export to dict and save as JSON)
2. I tried to convert class to dict (so that I can export as JSON)
cfg.__dict__ # {'NAME': 'ABC'}
vars(cfg) # {'NAME': 'ABC'}
In both cases, it was difficult to access attributes. Is it possible?
Configinto the file where your are trying to unpickle it.dillin place ofpickleto see if that works?cfg.__dict__doesn't include attributes from the class(es). Thedirfunction, or various functions ininspect, can get them. But then you need to filter out all kinds of things like methods and special attributes like__module__and so on, and… that's all doable if you understand the guts of Python classes well enough to come up with and then implement a suitable rule, but not usually a path worth going down for serialization.Configinstance, which is missing the same instance attributes, and therefore inherits the class attributes in the same way as the original, so it all just works—unless you're doing something uncommon and complicated, in which case you probably need to explain what that something is.