Commits

Jason R. Coombs committed cbd4217

Added bitutil.BitUtil metaclass

Comments (0)

Files changed (2)

   `key_match_comparator` for
   the constructor and `undefined_value`, `last_item`, and `first_item` class
   attributes.
+* Added `jaraco.util.bitutil.BitMask` metaclass.
 
 3.8.1
 ~~~~~

jaraco/util/bitutil.py

 		except TypeError:
 			index = self._names.index(key)
 			return self._values[index]
+
+class BitMask(type):
+	"""
+	A metaclass to create a bitmask with attributes. Subclass an int and
+	set this as the metaclass to use.
+	
+	>>> class MyBits(int):
+	...   __metaclass__ = BitMask
+	...   a = 0x1
+	...   b = 0x4
+	...   c = 0x3
+	
+	>>> b1 = MyBits(3)
+	>>> b1.a, b1.b, b1.c
+	(True, False, True)
+	>>> b2 = MyBits(8)
+	>>> any([b2.a, b2.b, b2.c])
+	False
+	"""
+
+	def __new__(cls, name, bases, attrs):
+		newattrs = dict(
+			(attr, property(lambda self, value=value: bool(self & value)))
+			for attr, value in attrs.items()
+			if not attr.startswith('_')
+		)
+		return type.__new__(cls, name, bases, newattrs)
+