[Python-ideas] constant/enum type in stdlib

Greg Ewing greg.ewing at canterbury.ac.nz
Sat Feb 2 02:41:01 CET 2013


Ethan Furman wrote:
> On 02/01/2013 04:53 PM, Greg Ewing wrote:
> 
>> The "obvious" way to spell this would be
>>
>>     from MyEnum import *
>>
>> but it would be challenging to make that work, I suspect. :-(
> 
> 
> It's not too tough:

Yeah, I just took up my own challenge and came up with something
similar (apologies for the Python 2):

   class MetaEnum(type):

     def __init__(self, name, bases, dict):
       type.__init__(self, name, bases, dict)
       import sys
       sys.modules[name] = self

   class Enum(object):
     __metaclass__ = MetaEnum		

   class MyEnum(Enum):
   RED = 0
   GREEN = 1
   BLUE = 2

   from MyEnum import *

   print RED
   print GREEN
   print BLUE

I left off the module name so that you don't have to qualify the
import. A more general version would qualify it with all but the
last component of the module name, so you can import it relative
to the containing module.

-- 
Greg



More information about the Python-ideas mailing list