[C++-sig] Iteration over an enumerated type
colin_irwin at hotmail.com
Thu Jan 27 07:33:01 CET 2005
One feature that I've occasionally used in C++ is to iterate over all types
of an enumerated type. This being possible if one defines the suitable
increment (or decrement) operator.
So in other words if one had the following enumerated type:
Value1, Value 2, Value3,
then the following code could be used, assuming that the increment operator
is defined for the enumerated type:
for ( KnownValue v = value1; v <= Value3; v++ )
I now have a need to do the same thing in Python, with an enumerated type
translated from C++. How does one do this?
Assuming the enumerated type is translated directly across from C++ into
Python (into the module my_module), then I'm been able to do:
begin = my_module.KnownValue.Value1
end = my_module.KnownValue.Value3
for v in range( start, end ):
I'm far from being an expert in Python, but this has the immediate problem
that the range function needs a type one beyond Value3 for the loop to
iterate over all useable types. (Indeed, this can also be required in C++
depending on how the loop is written.)
I was wondering whether there is a better way to do this in Python, without
having to add the extra type? Would it make sense to provide 'begin' and
'end' functions (an extra type to indicate the end would be required, but
given I'm talking about providing begin and end functions, then why not)?
These could be available in the module, such that the above for loop would
for v in range( my_module.KnownValue.begin(),
Writing this example out, I would be quite happy with this solution, but
does anyone have any other suggestions or experiences?
More information about the Cplusplus-sig