Last active
April 6, 2020 04:09
-
-
Save Billcountry/c5aec062c52bb09a29ff5c6e9096d743 to your computer and use it in GitHub Desktop.
An improvement over built in dictionary allowing you to access values using a `dot` notation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
class Dict(dict): | |
def __init__(self, **kwargs): | |
super(Dict, self).__init__() | |
for key, value in kwargs.items(): | |
self[key] = value # Takes advantage of __setitem__ logic | |
def __json__(self): | |
return json.dumps(self) | |
def __getattr__(self, name): | |
"""Allow dictionary access with a 'dot' notation. e.g. user.name""" | |
return self.get(name) | |
def __setattr__(self, key, value): | |
"""Set dictionary values with a 'dot' notation. e.g. user.name='Jane Doe'""" | |
return self.__setitem__(key, value) | |
def __setitem__(self, key, value): | |
if isinstance(value, dict) and not isinstance(value, Dict): | |
value = Dict(**value) | |
super(Dict, self).__setitem__(key, value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: