Joop
Joop

Reputation: 8118

Setting python class instance default variables from JSON file

Looking for an more elegant (and therefore) more robust way of doing this. Currently I have a class that has some default instance variables defined when it is created. I then read in a JSON file that allows the user to override some of these defaults. All of this code is in the init method of the class.

# Instance variables defaults 
self._a = 'A - original'
self._b = 'B - original'
self._c = 'C - original'

# line below gives example of dict that gets returned from the JSON read
JSON_dict = {'a': "A-overide", 'c': "C-overide"}

# Inelegent code:
if "a" in JSON_dict:
    self._a = JSON_dict['a']
if "b" in JSON_dict:
    self._b = JSON_dict['b']
if "c" in JSON_dict:
    self._c = JSON_dict['c']

The structure does not scale well. Any suggestions on how I can get the desired result in a more Pythonic way?

Not all variables need to be present in the dict from the JSON, but if they are they should overwrite the card coded ones.

Upvotes: 0

Views: 468

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

def __init__(self, ...):
  for key, val in JSON_dict.iteritems():
    setattr(self, '_%s' % (key,), val)

Upvotes: 1

Related Questions