Referring Enum members to each other
The way Python defines a class involves creating a new scope, processing a bunch of statements (variable assignments, function definitions, etc.), and then actually creating a class object based on the local variables which exist after all those statements have run. Nothing gets converted into Enum
instances until that last step.
You could understand it somewhat like this:
def make_class_Unit():
GRAM = ("g")
KILOGRAM = ("kg", GRAM, 1000.0)
def __init__(self, symbol, base_unit = None, multiplier = 1.0):
self.symbol = symbol
self.multiplier = multiplier
self.base_unit = self if base_unit is None else base_unit
return make_class(name='Unit', base=Enum, contents=locals())
Unit = make_class_Unit()
Looking at it this way, hopefully you can tell that at the time when KILOGRAM
is defined, GRAM
is really just a string. It doesn't become a Unit
instance until the last stage, where I call the (imaginary) make_class()
function.1
1Even though the make_class
function I used above doesn't actually exist under that name, it's not too different from what Python really does, which is calling the constructor of type
or a metaclass (which in this case is the metaclass for Enum
s).