close

How to compare a string with a python enum?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to compare a string with a python enum in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to compare a string with a python enum?

  1. How to compare a string with a python enum?

    One does not create an instance of an Enum. The Signal(foo) syntax is used to access Enum members by value, which are not intended to be used when they are auto().

  2. compare a string with a python enum

    One does not create an instance of an Enum. The Signal(foo) syntax is used to access Enum members by value, which are not intended to be used when they are auto().

Method 1

One does not create an instance of an Enum. The Signal(foo) syntax is used to access Enum members by value, which are not intended to be used when they are auto().

However one can use a string to access Enum members like one would access a value in a dict, using square brackets:

Signal[brain_detected_colour] is Signal.red

Another possibility would be to compare the string to the name of an Enum member:

# Bad practice:
brain_detected_colour is Signal.red.name

But here, we are not testing identity between Enum members, but comparing strings, so it is better practice to use an equality test:

# Better practice:
brain_detected_colour == Signal.red.name

(The identity comparison between strings worked thanks to string interning, which is better not to be relied upon.)

Yet another possibility would be to explicitly set the member values as their names when creating the Enum:

class Signal(Enum):
    red = "red"
    green = "green"
    orange = "orange"

Then, Signal(brain_detected_colour) is Signal.red would be valid.

Method 2

A better practice is to inherit Signal from str:

class Signal(str, Enum):
    red = 'red'
    green = 'green'
    orange = 'orange'

brain_detected_colour = 'red'
brain_detected_colour == Signal.red  # direct comparison

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read