dhp.structures¶
DictDot¶
DictDot subclasses Python’s built-in dict object and offers attribute access to the dictionary. A little code says alot:
from dhp.structures import DictDot
my_dict = {'hovercraft': 'eels', 'speed': 42}
dicdot = DictDot(my_dict)
assert dicdot.hovercraft == 'eels'
assert dicdot.speed == 42
# ok, how about this?
dicdot = DictDot(hovercraft='eels', speed=42)
assert dicdot.hovercraft == 'eels'
assert dicdot.speed == 42
# or if your attacker has a pointed stick
dicdot = DictDot(my_dict, bunch='bananas')
assert dicdot.speed == 42
assert dicdot.bunch == 'bananas'
dicdot.new_value = 17
assert dicdot['new_value'] == 17
assert dicdot['hovercraft'] == 'eels'
# and now this ...
import json
assert json.dumps(dicdot) == '{"new_value": 17, "speed": 42, "hovercraft": "eels", "bunch": "bananas"}'
All of the methods and functions of a normal Python dictionary are present and available for you to use.
Use case: Those times when you don’t want to type [”...”] but still want the goodness that is Python’s dictionary.
ComparableMixin¶
- To implment comparisions and sorting for your classes just subclass the mixin
- and then implement the _cmpkey() method:
from dhp.structures import ComparableMixin
class Comparable(ComparableMixin):
def __init__(self, value):
self.value = value
def _cmpkey(self):
return self.value
The magic methods lt, le, eq, ge, gt are all implemented and NotImplemented
is returned when appropriate. Easier to use than functools.total_ordering
.
see https://wiki.python.org/moin/HowTo/Sorting for information on how the
output of _cmpkey will sort.