Sunday 12 September 2021

Python: Compare two enum members for equality

You can compare two enum members for equality using either ‘is’ operator or == operator. Aliases comparison leads to True, you can confirm the same from below example.

 

enumComparison.py

from enum import Enum

class Test(Enum):        
    A = 1
    B = 1
    C = 23

print('Test.A == Test.A : ', (Test.A == Test.A))
print('Test.A is Test.A : ', (Test.A is Test.A))

# Aliases always return True
print('Test.A == Test.B : ', (Test.A == Test.B))
print('Test.A is Test.B : ', (Test.A is Test.B))

print('Test.A == Test.C : ', (Test.A == Test.C))
print('Test.A is Test.C : ', (Test.A is Test.C))

 

Output

Test.A == Test.A :  True
Test.A is Test.A :  True
Test.A == Test.B :  True
Test.A is Test.B :  True
Test.A == Test.C :  False
Test.A is Test.C :  False



 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment