Saturday 11 September 2021

Python: enum: aliases

In Python, two enum members are allowed to have same value.

 

For example,

If A and B are enum members with the same value and A defined first, the B is an alias to A.

 

How value lookup work on aliases?

Value lookup for A and B return A (Since A is defined first)

 

aliases1.py

from enum import Enum

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

print(Test(1))
print(Test(23))

 Output

Test.A
Test.C

How name lookup work on aliases?

Name lookup for A and B return A (Since A is defined first)

 

aliases2.py

from enum import Enum

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

print(Test.A)
print(Test.B)
print(Test.C)

 

Output

Test.A
Test.A
Test.C

 

How the iteration behaves with aliases?

Iterating over the members of an enum does not provide the aliases.

 

aliasesIteration.py

from enum import Enum

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

for member in Test:
    print(member, ' -> ', member.value)

 

Output

Test.A  ->  1
Test.C  ->  23

 

   

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment