Skip to content

Instantly share code, notes, and snippets.

@aamironline
Last active August 21, 2020 07:41
Show Gist options
  • Save aamironline/86510647ac08745fde5eccbce9080314 to your computer and use it in GitHub Desktop.
Save aamironline/86510647ac08745fde5eccbce9080314 to your computer and use it in GitHub Desktop.
"""
ISC License:
Copyright (c) 2020, Mohamed Aamir Maniar
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""
class DictObject(dict):
"""
A simple class that enhances the working with object by providing
synchronization mechanism with the base `dict`. Use as it is or as
a base class, it will make your objects behave like JavaScript objects.
Example:
>>> o = DictObject()
>>> o.a = 1
>>> o.b = 2
>>> print(o)
{'a': 1, 'b': 2}
>>> o['c'] = 3
>>> print(o)
{'a': 1, 'b': 2, 'c': 3}
>>> del o.a
>>> print(o)
{'b': 2, 'c': 3}
>>> del o['c']
>>> print(o)
{'b': 2}
>>> print(o.b)
2
>>> print(o['b'])
2
"""
# Attribute
def __setattr__(self, name, value):
dict.__setitem__(self, name, value)
return super().__setattr__(name, value)
def __delattr__(self, name):
dict.__delitem__(self, name)
return super().__delattr__(name)
# Items
def __setitem__(self, name, value):
dict.__setattr__(self, name, value)
return super().__setitem__(name, value)
def __delitem__(self, key):
dict.__delattr__(self, key)
return super().__delitem__(key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment