Hooky¶
Hooky is a Python Module have a list like object called List, and a dict like object called Dict.
The difference between UserList/UserDict and List/Dict is that List/Dict have four members which will call when List/Dict is changed.
Demo¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | from hooky import List, Dict
# List
class NameList(List):
def _before_add(self, key, item):
if not isinstance(item, str):
print('Type: {} is not well'.format(type(item)))
# of cause you may want raise here
else:
print('fine')
# two fine
names = NameList(['Sue', 'Alissa'])
# fine
names.append('ben')
# not well
names.append(b'Tom')
# Dict
class Files(Dict):
def _before_add(self, key, item):
if not isinstance(key, str):
raise TypeError
if '/' in key:
raise KeyError('invalid filename')
files = Files()
# fine
files['1.xml'] = '<test></test>'
# raise keyError:
files['tes/t.txt'] = b'text'
|
API Reference¶
-
class
hooky.
Hook
¶ -
_before_add
(key, item)¶ before add a item to the object will call this method.
example: obj[key] = item
-
_after_add
(key, item)¶ like _before_add, but after add.
-
_before_del
(key, item)¶ before delete a item from the object will call this method.
example: del obj[key]
-
_after_del
(key, item)¶ like _before_del, but after del.
-
-
class
hooky.
List
(initlist=None, hook_when_init=True)¶ Bases:
hooky.Hook
,collections.abc.Sequence
list like.
Parameters: - initlist – iterable object
- hook_when_init – run hook points when it is True
-
class
hooky.
Dict
(*args, **kwargs)¶ Bases:
hooky.Hook
,collections.abc.MutableMapping