Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums with Associated Values in Python

In Swift Enums have something called an Associated Value. Consider the following:

enum Shape {
     case circle(radius: Double)
     case rectangle(x: Double, y: Double)
}

In this case the Enums' Associated Values are radius and x & y and can be individually set for each instantiation of that Enum. E.g. I could do

smallCircle = Shape.circle(radius: 12)
largeCircle = Shape.circle(radius: 36)

Is there something similar for the Python Enum? I tried around myself but without much success. It seems like whatever attribute I set will always be the same for all instantiations of that Enum - i.e. in above example the second line equivalent in Python would have set the radius to 36 on both smallCircle and largeCircle. Any ideas?

like image 476
Jay Avatar asked Aug 09 '26 09:08

Jay


1 Answers

In Python, the value associated with the symbolic names of Enums can be of any type. Python Enum Documentation

Unlike Swift, from the Python documentation, the members of a Python Enum are functionally constant

So, the answer to your question is no.

like image 146
Pravin Damle Avatar answered Aug 11 '26 22:08

Pravin Damle