cleverdict icon indicating copy to clipboard operation
cleverdict copied to clipboard

Create converter for nested dictionaries / objects

Open PFython opened this issue 4 years ago • 2 comments

Create a new utility method (or enhance init?) to convert nested dictionaries into nested CleverDicts, so that deeper levels can be accesses easily with "." notation. For example:

>>> d = CleverDict({"level1": {"level2A": "A", "level2B": "B"}})
>>> d.level1.level2B
'B'
>>> d
CleverDict({'level1': CleverDict({'level2A': 'A', 'level2B': 'B'}, _aliases={}, _vars={})}, _aliases={}, _vars={})

I'd also like to extend this functionality to attributes, which might be trickier. For example:

>>> ac1 = AnotherClass()
>>> ac2 = AnotherClass()
>>> ac1.level2 = "Level Two"
>>> ac2.level1 = "Level One"
>>> d = CleverDict(ac1, ac2)
>>> d.ac1.level2
"Level Two"
>>> d.ac2.level1
"Level One"

And the absolute ideal would be to handle any mixture of dictionaries and objects/attributes. For example:

>>> d = CleverDict({"First Item":  {"level1": {"level2A": "A", "level2B": "B"}}},
                     ac1, {"Second Item": {"obj": ac2}}}
>>> d.First_Item.level1.level2A
"A"
>>> d.ac1.level2
"Level Two"
>>> d.Second_Item.obj.level1
"Level One"

PFython avatar Dec 02 '20 04:12 PFython

Labelled as "wontfix" after Version 1.8.0 simply because the main authors don't currently have the time for non essential enhancements. If there's a huge uptake in people using CleverDict and asking for this feature that may change, or if you're reading this why not Fork, develop a solution, and contribute a Pull Request yourself?

PFython avatar Jan 30 '21 00:01 PFython

Revisiting this after some time and while writing tests for my new Whatsapp class... I think the solution may be to set an option and if True, every time a new value is set, check to see if its value (or recursively, any of the values contained therein) is a Dictionary; if it is a dictionary, convert it to a cleverdict.

PFython avatar May 26 '22 15:05 PFython