How to Type Hint Enum in Python

Hey Python coder! In this tutorial, we will learn how to type hints in Enum using Python programming language. If you are unaware of what Enum is and how to implement it in Python, read the tutorial below.

Also Read: Implementation of enum in Python – CodeSpeedy

Enums, short for enumerations, allow you to create named constant values collectively at one place. Let’s start by creating a basic Enum for the colors mentioned in the spell book to make things interesting.

from enum import Enum

class Color(Enum):
    RED = 'Ruby Red'
    GREEN = 'Emerald Green'
    BLUE = 'Sapphire Blue'

For Spellbook, the colors might not be straightforward and must have some more specifications for the colors as mentioned above. Now, before the implementation of Type Hints, let’s start with understanding what Type Hints are in Enums.

Understanding Type Hints

Type Hints are a way to provide information to other Python developers about the kinds of values that are being used in our code and how they are supposed to work. To explain it much better, let’s take an example.

Let’s assume we have an Enum that contains a set of integers then one of the type hints that we can form is a function that performs addition on two elements with the type hint that could help get information that both the components are Integers.

Code Implementation of Type Hints in Enum

Let’s create a Type Hint function to reveal the color that goes puff from the spell as shown in the code snippet below. We create a function using the def keyword and to make it a type hint function we will pass the value c:Color as the argument. The argument implies that the function takes a single variable called c which is of type Color.

def reveal_spell_color(c: Color):
    print(f"The crystal reveals: {c.value}")
    
reveal_spell_color(Color.RED)

The output of the code comes out as Ruby Red which is the color that corresponds to the color RED.

Final Code and Output

Have a look at the screen snip below to understand what the final output looks like.

How to Type Hint Enum in Python - Output

Conclusion

Type Hints in Enum helps to improve code clarity and makes it more readable and understandable. By using them, you can provide additional information to yourself as well as others who later come across your code.

The concept of Type Hints is pretty much simple and clear! I hope you understood the concept clearly.

Also Read:

  1. Implement an Interface using an Enum in Java – CodeSpeedy
  2. Conversion of String to Enum in Java – CodeSpeedy
  3. enum.IntEnum in Python with Examples – CodeSpeedy

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *