However, the _generate_next_value_() function can be overwritten to generate new values the way you like: # overwritten_next_values.pyĭef _generate_next_value_(name, start, count, last_values):īeing Python classes, enums can have any (special) methods just like all other classes.Ĭonsider the following example. It chooses a suited value for each enum member, which will (most of the time) be the integers we used before. The function calls _generate_next_value_() internally and generates the values for you. If the exact values are not important, you can use the to() function. In the previous example, we assigned integers to the symbolic names RED, GREEN, and BLUE. However, if you have an enumeration that has aliases, too, only the approach using _members_ will print the aliases as well.Ĭheckout the following example: # iterate_alias.py You might ask yourself why we did not something like: for member in Colour:įor the example at hand, both approaches produce the same result. # iterate.pyįor name, member in Colour._members_.items(): Utilising _members_ allows you to iterate over an enum and print the members as well as their corresponding names. Iterating Over the Members of an Enum ¶Įnumerations have a special attribute called _members_, which is a read-only ordered mapping of names and members. Keep in mind that enums can only be compared to enums and not to integers, even though the enum member values are integers. Note: We used the is operator to compare the variable c with the different enum members. Running the script reveals that c is indeed an instance of Colour.RED with RED as its name and 1 as value. We extended the colour.py script by creating a new instance of Colour.RED and assigning it to the variable c.įurthermore, we print the string representation of Colour.RED, its name and value.Īdditionally, we compare c's identity with Colour.RED and Colour.BLUE. If you want to know more about it, check out the How are Enums different? section in the module's documentation : Note: Although the class syntax is used to define new enumerations, they aren't normal Python classes. Subsequently, a new enum called Colour is implemented having three enum members: RED, GREEN, and BLUE. It serves as a base class for defining new enumerations in Python. We imported the Enum class from Python's enum module. The following code snippet shows you a simple example of an enum Colour: # colour.py You can iterate over an enumeration and compare its members by identity (Python's is operator). These enum members are bound to unique, constant values. What Is an Enum? ¶Įnum stands for enumeration and refers to a set of symbolic names, which are called enumeration members. The code snippets used in the article can be found on GitHub.
0 Comments
Leave a Reply. |