0

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?

Ken S
  • 315
  • 1
  • 3
  • 11
  • Can't you just edit the original Dictionary and then call the dict2struct() function again? – Alvi15 Nov 13 '20 at 03:46
  • So are you looking for a dictionary-like object that lets you set key/value pairs via `x.key = value`? I wrote one of those a long time ago that I've been using ever since. I was just googling around, and didn't find anything similar that didn't come as part of a huge collection of stuff. I'm surprised. I wonder if someone else knows of one of these available in the wild pretty much on its own. Maybe I should publish mine :) – CryptoFool Nov 13 '20 at 03:55
  • @Steve, the input I have is a dictionary with string keys. The output is supposed to be a struct / class so as to be used like: res.fieldx, res.fieldy, etc. Can you share a bit of your code of the conversion? – Ken S Nov 13 '20 at 03:58
  • 1
    Ah. Found it. Is this what you want maybe? - https://pypi.org/project/attributedict/ – CryptoFool Nov 13 '20 at 04:03
  • This sounds like an [x y problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). What problem are you trying to solve with it? – Klaus D. Nov 13 '20 at 04:03
  • @Steve attributedict works for me. Thanks a lot! – Ken S Nov 13 '20 at 04:26

1 Answers1

0

Steve's solution above worked for me. pypi.org/project/attributedict

Ken S
  • 315
  • 1
  • 3
  • 11