Named bitmap

Every now and then, one needs to keep track of a family of flags (boolean values), which you naturally would store in a numerical field which saves a lot of space and is database-friendly. Although the bit algrebra is straightforward, one often wishes to abstract that a little bit and to access the flags as attributes of some instance, pretty much like the awesome namedtuple helps so much to clarify what entry 42 of that tuple was for again, in particular if some slot is being added or removed. So here it is:

A little test run follows:

>>> test = bitmap('test', ['a', 'b', 'c'])
>>> t = test(5)
>>> t
>>> t.a
>>> t.a = 0
>>> t
>>> list(t)
[False, False, True]
>>> dict(zip(t.fields, t))
{'a': False, 'c': True, 'b': False}


comments powered by Disqus