简体   繁体   中英

Pythonic way to serialize static class variables to json

I wish to serialize an entire class to json. However, most of the variables I need are static variables (not defined within __init__() ). Is there a Pythonic way to do that, other then the naive solution, ie, calling all variables by name?

So far, I tried to call json.dump() with an encoder to handle numpy arrays:

cfg = MyConfig(Config)

class NumpyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.ndarray):
            return obj.tolist()
        return json.JSONEncoder.default(self, obj)

with open(os.path.join(logs_dir, 'config.json'), 'w') as file:
    json.dump(cfg.__dict__, file, cls = NumpyEncoder)

However (of course) this snippet only took care of the three variables that are declared in __init__() , and left out the static vars.

More info, just in case: I want to serialize a class that inherits from config in Mask RCNN .

So, I did some research and found a solution, just in case someone gets here via Google. The way to save all the class variables, even the static ones, is to call json.dump() with the class name, and not the instance name, like so:

with open(os.path.join(logs_dir, 'config.json'), 'w') as file:
        json.dump(Config.__dict__.copy(), file, cls = NumpyEncoder)

The reason I call copy() on Config.__dict__ is that calling __dict__ on the class (not instance) returns a mappingproxy object, which cannot naively be written to json using dump() . Coping the object turns it into a dictionary, which fixed the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM