[Python-ideas] constant/enum type in stdlib

Antoine Pitrou solipsis at pitrou.net
Wed Jan 30 17:23:10 CET 2013


Le Wed, 30 Jan 2013 15:16:49 +0000,
Michael Foord <fuzzyman at gmail.com> a
écrit :
> 
> Being an int subclass (and possibly optionally a strs subclass) is a
> requirement if any adopted Enum is to be used *within* the standard
> library in places where integers are currently used as "poor man's
> enums". I also don't *think* flufl.enum supports flag enums (ones
> that can be OR'd together), right?

If a flexible solution is desired (with either int or str subclassing,
various numbering schemes), may I suggest another kind of syntax:

class ErrorFlag(Enum):
    type = 'symbolic'
    names = ('strict', 'ignore', 'replace')

class SeekFlag(Enum):
    type = 'sequential'
    names = ('SET', 'CUR', 'END')

class TypeFlag(Enum):
    type = 'bitmask'
    names = ('HEAPTYPE', 'HAS_GC', 'INT_SUBCLASS')


>>> ErrorFlag.ignore
ErrorFlag.ignore
>>> ErrorFlag.ignore == 'ignore'
True
>>> ErrorFlag('ignore')
ErrorFlag.ignore
>>> isinstance(ErrorFlag.ignore, str)
True
>>> isinstance(ErrorFlag.ignore, int)
False
>>> ErrorFlag(0)
[...]
ValueError: invalid value for <class 'enum.ErrorFlag'>: 0

>>> SeekFlag('SET')
SeekFlag.SET
>>> SeekFlag('SET') + 0
0
>>> SeekFlag(0)        
SeekFlag.SET
>>> isinstance(SeekFlag.CUR, int)
True
>>> isinstance(SeekFlag.CUR, str)
False

>>> TypeFlag(1)
TypeFlag.HEAPTYPE
>>> TypeFlag(2)
TypeFlag.HAS_GC
>>> TypeFlag.HAS_GC | TypeFlag.INT_SUBCLASS
6


Regards

Antoine.





More information about the Python-ideas mailing list