7

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?

4
  • 2
    This seems more like a class/subclass relationship to me -- e.g. a base class Shape that's empty and then derived classes Circle and Rectangle with the appropriate attributes (possibly defined with @dataclass). Does that have the semantics you'd be looking for? Commented Dec 24, 2022 at 16:03
  • Do you intend to make an unlimited number of circles, or just a few fixed types? Commented Dec 24, 2022 at 19:36
  • Its the former, i.e. a large number - that is the whole point and the nice thing about the way it is implemented in Swift. Was hoping to be able to re-create something similar in Python but seems like its not possible. Imagine the example above where you would also have nome cases with no attributes at all (in mz practical problem at hand thats the case). Commented Dec 24, 2022 at 20:03
  • enum members are meant to be singletons. You probably just don't want to use enums in Python, what is your use-case? There is something probably more appropriate with python Commented Jan 20, 2023 at 0:33

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yes, enum members are meant to be singletons.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.