HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

An attempt at a simple type safe python enum

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simpleenumattempttypepythonsafe

Problem

There have been many posts here about enums in python, but none seem to be both type safe and simple. Here is my attempt at it. Please let me know if you see anything obviously wrong with it.

def typeSafeEnum(enumName, *sequential):
    topLevel = type(enumName, (object,), dict(zip(sequential, [None] * len(sequential))))
    vals = map(lambda x: type(x,(topLevel,),{}), sequential)
    for k, v in zip(sequential, vals):
        setattr(topLevel, k, v())
    return topLevel


Then to test it:

Colors = typeSafeEnum('Colors', 'RED', 'GREEN', 'BLUE')

if __name__ == '__main__':
    x = Colors.RED
    assert isinstance(x, Colors)

Solution

def typeSafeEnum(enumName, *sequential):


Python convention is lowercase_with_underscores for functions and parameters. Although since this is a type factory its not totally clear what convention should appply. I also wonder if passing the enum values as a list might be better.

topLevel = type(enumName, (object,), dict(zip(sequential, [None] * len(sequential))))


There is no point in the dict you are passing since you just setattr all the enums in place already. Here you set all the enum values up with None initially and then fill them in. Why? I can also see why you call this topLevel but its not an immeadiately obvious name

vals = map(lambda x: type(x,(topLevel,),{}), sequential)


List comprehensions are generally preffered to calling map with a lambda. But also, why? Just do this in the for loop. You don't gain anything by having it done in a map and then zipping over it.

for k, v in zip(sequential, vals):


I suggest longer less abbreviated names

setattr(topLevel, k, v())
    return topLevel

Code Snippets

def typeSafeEnum(enumName, *sequential):
topLevel = type(enumName, (object,), dict(zip(sequential, [None] * len(sequential))))
vals = map(lambda x: type(x,(topLevel,),{}), sequential)
for k, v in zip(sequential, vals):
setattr(topLevel, k, v())
    return topLevel

Context

StackExchange Code Review Q#24536, answer score: 3

Revisions (0)

No revisions yet.