2

I've been using this for a while - I can't recall where I found it:

#####
#  An enumeration is handy for defining types of event 
#  (which otherwise would messily be just random strings)

def enum(**enums):
    return type('Enum', (), enums)

#####
#   The control events that the Controller can process
#   Usually this would be in a module imported by each of M, V and C
#   These are the possible values for the "event" parameter of an APP_EVENT message

AppEvents = enum(APP_EXIT = 0,
                 CUSTOMER_DEPOSIT = 1,
                 CUSTOMER_WITHDRAWAL = 2)

How does it work?

GreenAsJade
  • 14,459
  • 11
  • 63
  • 98

1 Answers1

3

When called in that way, type declares a type dynamically. From the docs:

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the name attribute; the bases tuple itemizes the base classes and becomes the bases attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the dict attribute.

So the type name is 'Enum' and there are no base classes.

The enum function has a **enums argument, which takes all named parameters and puts them into a dictionary object.

In your case, the enums variable is

{
    'APP_EXIT': 0,
    'CUSTOMER_DEPOSIT':  1,
    'CUSTOMER_WITHDRAWAL': 2,
}

Those become the attributes of the returned type.


FYI, Enum has been added to Python 3.4 and backported to 2.4+. (see also How can I represent an 'Enum' in Python?).

Community
  • 1
  • 1
Paul Draper
  • 78,542
  • 46
  • 206
  • 285