Last active
February 26, 2020 09:16
-
-
Save swnim/27049ca3491147cadbfaf4dfc2ec56eb to your computer and use it in GitHub Desktop.
Dot Notation - ref. https://stackoverflow.com/questions/2352181/how-to-use-a-dot-to-access-members-of-dictionary
This file contains hidden or 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
class DotMap(dict): | |
"""Dot.Notation access to dictionary attributes""" | |
__getattr__ = dict.get | |
__setattr__ = dict.__setitem__ | |
__delattr__ = dict.__delitem__ |
This file contains hidden or 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
class Map(dict): | |
""" | |
Example: | |
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer']) | |
""" | |
def __init__(self, *args, **kwargs): | |
super(Map, self).__init__(*args, **kwargs) | |
for arg in args: | |
if isinstance(arg, dict): | |
for k, v in arg.items(): | |
self[k] = v | |
if kwargs: | |
for k, v in kwargs.items(): | |
self[k] = v | |
def __getattr__(self, attr): | |
return self.get(attr) | |
def __setattr__(self, key, value): | |
self.__setitem__(key, value) | |
def __setitem__(self, key, value): | |
super(Map, self).__setitem__(key, value) | |
self.__dict__.update({key: value}) | |
def __delattr__(self, item): | |
self.__delitem__(item) | |
def __delitem__(self, key): | |
super(Map, self).__delitem__(key) | |
del self.__dict__[key] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment