I was running python code below:
def dict2struct(d):
res = namedtuple("config", d.keys())(*d.values())
return res
cfg = {'fieldx': 'Allan', "fieldy": 45, 'fieldt': {'head': False, 'number': 2}}
res = dict2struct(cfg)
print(res)
res.fieldx = "Jack"
and got the error:
config(fieldx='Allan', fieldy=45, fieldt={'head': False, 'number': 2})
Traceback (most recent call last):
File "*****\Testings\test_x.py", line 97, in <module>
res.fieldx = "Jack"
AttributeError: can't set attribute
I have read the questions below and understand that it was because namedtuples
are immutable and the property setter was restricted.
AttributeError: can't set attribute
AttributeError: can't set attribute in python
However, I need to convert a lot of strings from a configurational dictionary's keys to properties of a struct or a class. These strings values are not fixed as they are many.
Is there a way to get around of this AttributeError
for my problem?