{"id":182,"date":"2024-01-25T15:03:01","date_gmt":"2024-01-25T15:03:01","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=182"},"modified":"2024-01-25T15:03:02","modified_gmt":"2024-01-25T15:03:02","slug":"python-enumeration","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/01\/25\/python-enumeration\/","title":{"rendered":"Python Enumeration"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you\u2019ll learn about Python enumeration and how to use it effectively.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the Python Enumeration<\/h2>\n\n\n\n<p>By definition, an enumeration is a set of members that have associated unique constant values. Enumeration is often called enum.<\/p>\n\n\n\n<p>Python provides you with the\u00a0<code>enum<\/code>\u00a0module that contains the\u00a0<code>Enum<\/code>\u00a0type for defining new enumerations. And you define a new enumeration type by\u00a0subclassing\u00a0the\u00a0<code>Enum<\/code>\u00a0class.<\/p>\n\n\n\n<p>The following example shows how to create an enumeration called\u00a0<code>Color<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, import the\u00a0<code>Enum<\/code>\u00a0type from the\u00a0<code>enum<\/code>\u00a0module:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from enum import Enum<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Second, define the\u00a0<code>Color<\/code>\u00a0class that inherits from the\u00a0<code>Enum<\/code>\u00a0type:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Color(Enum):<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Third, define the members of the\u00a0<code>Color<\/code>\u00a0enumeration:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>RED = 1 GREEN = 2 BLUE = 3<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Note that the enumeration\u2019s members are constants. Therefore, their names are in uppercase letters by convention.<\/p>\n\n\n\n<p>In this example, the&nbsp;<code>Color<\/code>&nbsp;is an enumeration. The&nbsp;<code>RED<\/code>,&nbsp;<code>GREEN<\/code>, and&nbsp;<code>BLUE<\/code>&nbsp;are members of the&nbsp;<code>Color<\/code>&nbsp;enumeration. They have associated values 1, 2, and 3.<\/p>\n\n\n\n<p>The type of a member is the enumeration to which it belongs.<\/p>\n\n\n\n<p>The following illustrates that the type of\u00a0<code>Color.RED<\/code>\u00a0is the\u00a0<code>Color<\/code>\u00a0enumeration:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(type(Color.RED))<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>&lt;enum 'Color'><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The\u00a0<code>Color.RED<\/code>\u00a0is also an instance of the\u00a0<code>Color<\/code>\u00a0enumeration:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(isinstance(Color.RED, Color))<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>True<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>And it has the name and value attributes:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(Color.RED.name) print(Color.RED.value)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>RED 1<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Membership and equality<\/h2>\n\n\n\n<p>To check if a member is in an enumeration, you use the\u00a0<code>in<\/code>\u00a0operator. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>if Color.RED in Color: print('Yes')<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>Yes<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>To compare two members, you can use either\u00a0<code>is<\/code>\u00a0or\u00a0<code>==<\/code>\u00a0operator. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>if Color.RED is Color.BLUE: print('red is blue') else: print('red is not blue')<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>red is not blue<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Note that a member and its associated value are not equal. The following example returns\u00a0<code>False<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>if Color.RED == 1: print('Color.RED == 1') else: print('Color.RED != 1')<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>Color.RED != 1<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Enumeration members are hashable<\/h2>\n\n\n\n<p>Enumeration members are always\u00a0hashable. It means that you can use the enumeration members as keys in a\u00a0dictionary\u00a0or as elements of a\u00a0Set.<\/p>\n\n\n\n<p>The following example uses the members of the\u00a0<code>Color<\/code>\u00a0enumeration in a dictionary:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>rgb = { Color.RED: '#ff0000', Color.GREEN: '#00ff00', Color.BLUE: '#0000ff' }<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Access an enumeration member by name and value<\/h2>\n\n\n\n<p>The typical way to access an enumeration member is to use the dot notation (.) syntax as you have seen so far:<code>Color.RED<\/code><small>Code language: Python (python)<\/small><\/p>\n\n\n\n<p>Because the&nbsp;<code>Enum<\/code>&nbsp;implements the&nbsp;<code>__getitem__<\/code>&nbsp;method, you can also use a square brackets&nbsp;<code>[]<\/code>&nbsp;syntax to get a member by its name.<\/p>\n\n\n\n<p>For example, the following uses the square brackets\u00a0<code>[]<\/code>\u00a0syntax to get the\u00a0<code>RED<\/code>\u00a0member of the\u00a0<code>Color<\/code>\u00a0enumeration by its name:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(Color&#91;'RED'])<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>Color.RED<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Since an enumeration is\u00a0callable, you can get a member by its value. For example, the following return the\u00a0<code>RED<\/code>\u00a0member of the\u00a0<code>Color<\/code>\u00a0enumeration by its value:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(Color(1))<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>Color.RED<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The following expression returns\u00a0<code>True<\/code>\u00a0because it accesses the same enumeration member using name and value:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(Color&#91;'RED'] == Color(1))<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>True<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Iterate enumeration members<\/h2>\n\n\n\n<p>Enumerations are iterables so you can iterate them using a\u00a0<code>for<\/code>\u00a0loop. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>for color in Color: print(color)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>Color.RED Color.GREEN Color.BLUE<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Notice that the order of the members is the same as in the enumeration definition.<\/p>\n\n\n\n<p>Also, you can use the\u00a0<code>list()<\/code>\u00a0function to return a list of members from an enumeration:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(list(Color))<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>&#91;&lt;Color.RED: 1>, &lt;Color.GREEN: 2>, &lt;Color.BLUE: 3>]<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Enumerations are immutable<\/h2>\n\n\n\n<p>Enumerations are\u00a0immutable. It means you cannot add or remove members once an enumeration is defined. And you also cannot change the member values.<\/p>\n\n\n\n<p>The following example attempts to assign a new member to the\u00a0<code>Color<\/code>\u00a0enumeration and causes a\u00a0<code>TypeError<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>Color&#91;'YELLOW'] = 4<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>TypeError: 'EnumMeta' object does not support item assignment<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>The following example attempts the change the value of the\u00a0<code>RED<\/code>\u00a0member of the\u00a0<code>Color<\/code>\u00a0enumeration and causes an\u00a0<code>AttributeError<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>Color.RED.value = 100<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>AttributeError: can't set attribute<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Inherits from an enumeration<\/h2>\n\n\n\n<p>An enumeration cannot be inherited unless it contains no members. The following example works fine because the\u00a0<code>Color<\/code>\u00a0enumeration contains no members:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class Color(Enum): pass class RGB(Color): RED = 1 GREEN = 2 BLUE = 3<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>However, the following example won\u2019t work because the\u00a0<code>RGB<\/code>\u00a0enumeration has members:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class RGBA(RGB): ALPHA = 4<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>TypeError: Cannot extend enumerations<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Python enumeration example<\/h2>\n\n\n\n<p>The following example defines an enumeration called\u00a0<code>ResponseStatus<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>class ResponseStatus(Enum): PENDING = 'pending' FULFILLED = 'fulfilled' REJECTED = 'rejected'<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Suppose you receive a response from an HTTP request with the following string:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>response = '''{ \"status\":\"fulfilled\" }'''<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>And you want to look up the\u00a0<code>ResponseStatus<\/code>\u00a0enumeration by the\u00a0<code>status<\/code>. To do that, you need to convert the response\u2019s string to a dictionary and get the value of the status:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>import json data = json.loads(response) status = data&#91;'status']<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>And then you look up the member of the\u00a0<code>ResponseStatus<\/code>\u00a0enumeration by the status\u2019 value:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(ResponseStatus(status))<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>PromiseStatus.FULFILLED<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Here\u2019s the complete program:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from enum import Enum import json class ResponseStatus(Enum): PENDING = 'pending' FULFILLED = 'fulfilled' REJECTED = 'rejected' response = '''{ \"status\":\"fulfilled\" }''' data = json.loads(response) status = data&#91;'status'] print(ResponseStatus(status))<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>What if the\u00a0<code>status<\/code>\u00a0is not one of the values of the\u00a0<code>ResponseStatus<\/code>\u00a0members? then you\u2019ll get an error. For example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from enum import Enum import json class ResponseStatus(Enum): PENDING = 'pending' FULFILLED = 'fulfilled' REJECTED = 'rejected' response = '''{ \"status\":\"ok\" }''' data = json.loads(response) status = data&#91;'status'] print(ResponseStatus(status))<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Error:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>ValueError: 'ok' is not a valid ResponseStatus<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>To catch the exception, you can use the\u00a0<a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-try-except\/\">try\u2026except<\/a>\u00a0statement like the following:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from enum import Enum import json class ResponseStatus(Enum): PENDING = 'pending' FULFILLED = 'fulfilled' REJECTED = 'rejected' response = '''{ \"status\":\"ok\" }''' data = json.loads(response) status = data&#91;'status'] try: if ResponseStatus(status) is ResponseStatus.FULFILLED: print('The request completed successfully') except ValueError as error: print(error)<\/code><\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you\u2019ll learn about Python enumeration and how to use it effectively. Introduction to the Python Enumeration By definition, an enumeration is a set of members that have associated unique constant values. Enumeration is often called enum. Python provides you with the\u00a0enum\u00a0module that contains the\u00a0Enum\u00a0type for defining new enumerations. And you define [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[29],"tags":[],"class_list":["post-182","post","type-post","status-publish","format-standard","hentry","category-5-enumeration"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/182","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=182"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/182\/revisions"}],"predecessor-version":[{"id":183,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/182\/revisions\/183"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=182"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=182"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=182"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}