drgrib / dotmap

Dot access dictionary with dynamic hierarchy creation and ordered iteration

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Accessing a key that does not exist does not through an error

shivakumargn opened this issue · comments

commented

A dictionary throws an exception when a key that does not exist is accessed while DotMap does not.
It ideally should.

>>> from dotmap import DotMap
>>> a = { 'x':'one' }
>>> b = DotMap(a)
>>> a['y']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'y'
>>> b.y
DotMap()

Implementing this would break the automatic hierarchy feature:

m = DotMap()

m.people.john.age = 32
m.people.john.job = 'programmer'

@drgrib I believe that the vast majority of people would prefer to have exception thrown for non-existing keys, over having hierarchical support.

Another idea is to throw exceptions when _dynamic=False

of course, I may be wrong :)

Maybe it's worth checking how it works here:
https://github.com/bcj/AttrDict

@YoelShoshan As the creator, I designed it as one of my core features. So I have to disagree with you, even if I am the only one.

Perfectly understandable, thanks for sharing this repository either way :)
I switched to "munch" - which supports what I specifically need.

P.S. - I didn't dive too deeply, from a shallow look it seems that they support both options - recursive attributes and throwing exceptions on invalid entries. https://github.com/Infinidat/munch

Cheers.

@YoelShoshan Thanks. dotmap supports both options too. You can find it in the readme under DotMap(_dynamic=False).