base.enum

Better Named Constants

Yes, Python has an enum library, but this one is better.

At a Glance

An Enum is a list of named constants.

In the simplest form, you define an Enum like this:

base.Enum.Define('MyEnum', (
    'First',
    'Second',
    'Third',
))

This defines for you global variables that acts like this:

MYENUM_FIRST = 'F'
MYENUM_SECOND = 'S'
MYENUM_THIRD = 'T'

In actuality, each of these constants is not a str, but a base.StrOption instance, which derives from str and base.Option together.

Additionally, a MyEnum instance of Enum is also created and entered into the global namespace, and allows access to all the related options as a group.

Deeper

Every part of this enum definition can be expanded.

Singular/Plural

Firstly, the name of the enum itself can be changed from MyEnum into a tuple of singular/plural forms:

base.Enum.Define(('MYENUM', 'MyEnums'), (
  ...

The singular form is used as the prefix for each option’s definition. We’ve capitalized it here because it’s always capitalized when the options are added to your module’s globals. The plural form is used for the Enum instance.

Option Details

More interestingly, each option can be a tuple of 1, 2, 3, or 4 parts:

base.Enum.Define(('MYENUM', 'MyEnums'), (
    'Bare String',                        #  name
    ('1-Tuple', ),                        # (name, )
    ('2-Tuple', 'two'),                   # (name, tag)
    ('3-Tuple', 'three', 'THREE'),        # (name, tag, code_name)
    ('cat', '4-Tuple', 'four', 'FOUR')    # (icon, name, tag, code_name)
))

Here, the options that are introduced look like this:

MYENUM_BARE_STRING    = 'B'
MYENUM_1_TUPLE        = '1'
MYENUM_2_TUPLE        = 'two'
MYENUM_THREE          = 'three'
MYENUM_FOUR           = 'four'

Specifically:

  • On a 1-tuple, you’re giving just the option’s human-readable name, and the value of that option is set to the first character of the name
  • On a 2-tuple, you’re giving the name and the value of that option, which we call the option’s “tag”
  • On a 3-tuple you’re giving the name, the tag, and the python code-name as well. Note the code-name will be fully uppercased, always.
  • On a 4-tuple you get to also specify an “icon” property

The Enum Object

Each defined Enum creates an object that can map back and forth between names and tags. Continuing our example, the object that’s created was called MyEnums and it has all these methods:

  • MyEnums.Tag(value)
  • MyEnums.Name(value)
  • MyEnums.Icon(value)

Each of these methods takes either the human-readable name or the tag of an option:

MyEnums.Tag('two') == 'two'
MyEnums.Name('two') == '2-tuple'

MyEnums.Tag('2-tuple') == 'two'
MyEnums.Name('2-tuple') == '2-tuple'

There are a couple other useful functions on MyEnums as well:

  • .MaxTagLength() – returns an integer for how many characters are needed for the longest tag
  • .Choices() – returns a list: [ (name, tag), ... ]
    • this is exactly what Django expects as a choices= attribute on a field

As well, several of the pythonic shortcuts are enabled:

  • if tag in MyEnums
  • for tag in MyEnums
  • len(MyEnums)

Option Objects

Each of the enum option definitions is actually a class instance that tries very hard to act like the atomic type that underlies it.

That is, Enums work with two types of tag data, strings and ints. There are two corresponding types of options we work with: StrOption and IntOption, which derive from str and int respectively, as well as both being subclasses of base.Option

any enum may also contain a single option with a tag of None, and as such there is also a NoneOption

An Option instance provides easy access to all the parts of the option’s definition:

MYENUM_FOUR.name == '4-Tuple'
MYENUM_FOUR.icon == 'cat'

it also has a couple other properties of use:

  • .enum – a reference to the Enum that the Option belongs to
  • .tag – returns the atomic equivalence of the Option
  • .index – returns the ordinal of this Option’s position in the Enum
  • .rank – maps the .index into a range of [0..1] for this Enum

Deepest Depths Yet

A few clarifications on the above:

Strings, Ints, and None

A Enum must be defined with tags that are all strings, or tags that are all integers. Additionally, a single option in any Enum may have a tag of None.

Icons

There is nothing specifically iconic about an option’s icon attribute, it’s just another attribute that holds an arbitrary string.

Adding to Existing Enums

An Enum that has already been defined can be extended:

MyEnum.Add('5th Option', '5', '5th')

This adds another option to an existing enum. Note that no matter where this addition is called from, the new option is added to the globals of the module that the enum itself lives within.

More Attributes On Each Option

If you want more attributes than name, tag, and icon, you can add your own by using a dictionary instead of a tuple as the option definition:

{'name': '6th Option', 'tag': '6', 'codename': '6th', 'my_extra_attr': some_instance}

This new attribute then is exposed on your Option:

assert(MYENUM_6TH.my_extra_attr == some_instance)

This works either in the original Define(...) or as an Add(...).

Nested Enums

There is limited support for hierarchical enums. Instead of Enum.Define(...) you would use:

MyEnum.DefineNested(
    parent_option_definition,
    (
        sub_option_definition,
        sub_option_definition,
        # ... more ...
    )
)

Nested option tags are simply concatenated with their parent option tags, which is probably not ideal in many cases but works perfectly fine in the one single case we wrote this to handle – our FileTypes. Enum “in” testing should work as you expect though, where any option is considered “in” its parent enums as well as its own.