Welcome, guest | Sign In | My Account | Store | Cart
class constant(int):
    """A constant type which overrides base int to provide a useful name on str().
    Example:

    >>> STATUS_RUNNING = constant(0, 'running')
    >>> STATUS_RUNNING  
    0
    >>> str(STATUS_RUNNING)
    'running'
    >>>
    """

    def __new__(cls, value, name, doc=None):
        inst = super(constant, cls).__new__(cls, value)
        inst._name = name
        if doc is not None:
            inst.__doc__ = doc
        return inst

    def __str__(self):
        return self._name

    def __eq__(self, other):
        if isinstance(other, int):
            return int(self) == other
        if isinstance(other, str):
            return self._name == other
        return False

    def __ne__(self, other):
        return not self.__eq__(other)

Diff to Previous Revision

--- revision 6 2012-06-13 13:26:35
+++ revision 7 2012-06-13 13:43:47
@@ -21,13 +21,6 @@
         return self._name
 
     def __eq__(self, other):
-        # use both int and str values when comparing for equality
-        # (useful for serialization):
-        # >>> st = constant(0, "running")
-        # >>> st == 0
-        # True
-        # >>> st == 'running'
-        # True
         if isinstance(other, int):
             return int(self) == other
         if isinstance(other, str):

History