We can create our own class to use the dot syntax to access a dictionary's keys.
class DictX(dict):
def __getattr__(self, key):
try:
return self[key]
except KeyError as k:
raise AttributeError(k)
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
try:
del self[key]
except KeyError as k:
raise AttributeError(k)
def __repr__(self):
return '<DictX ' + dict.__repr__(self) + '>'
Our class DictX
here inherit Python's builtin dict
.
Now use it we just need to wrap a native dictionary with this DictX
class:
data = DictX({
"name": "bo"
})
# use dot to get
print(data.name)
print(data["name"])
# use dot to set
data.state = "NY"
print(data.state)
print(data["state"])
# use dot to delete
del data.state
print(data)
Printed result:
bo
bo
NY
NY
<DictX {'name': 'bo'}>
Top comments (4)
This is such a fun example of how easy it is to be creative and make your own implementation of anything in python.
I often use simple namespaces or data classes to get this effect with vanilla types.
It is always good to use builtins like SimpleNamespace. But if you really need something advanced to crawl through structures by dot notation then you should try Jsify library (citsystems.github.io/jsify/)
How would implement:
foo["bar"]["baz"]
to be equal tofoo.bar.baz
?You can try this, change the
__getattr__
to:Then use it:
Result: