Quantcast
Channel: Recent Gists from brainsik
Viewing all articles
Browse latest Browse all 30

Override Python's dict with this for JS style dot notation access :-)

$
0
0
dotdict.py
# encoding: utf-8
classDotDict(dict):
def__init__(self, *a, **kw):
dict.__init__(self, *a, **kw)
forkeyinself:
self._validate_key(key)
def_validate_key(self, key):
try:
classIsIdentifier(object): __slots__=key
exceptTypeError:
raiseTypeError("invalid identifier: '%s'"%key)
try:
dict.__getattribute__(self, key)
exceptAttributeError:
pass
else:
raiseTypeError("builtin dict attribute: '%s'"%key)
def__getattribute__(self, name):
try:
returndict.__getattribute__(self, name)
exceptAttributeError:
ifnameinself:
returnself[name]
raise
def__setitem__(self, key, value):
self._validate_key(key)
dict.__setitem__(self, key, value)
__setattr__=__setitem__
__delattr__=dict.__delitem__
defcopy(self, *a, **kw):
obj=dict.copy(self, *a, **kw)
ifobj.__class__isDotDict.__class__:
returnobj
returnDotDict(obj)
@classmethod
deffromkeys(cls, *a, **kw):
obj=super(DotDict, cls).fromkeys(*a, **kw)
ifobj.__class__isDotDict.__class__:
returnobj
returncls(obj)

Viewing all articles
Browse latest Browse all 30

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>