Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No need for enums

Tags:

python

I read a post recently where someone mentioned that there is no need for using enums in python. I'm interested in whether this is true or not.

For example, I use an enum to represent modem control signals:

class Signals:
  CTS = "CTS"
  DSR = "DSR"
  ...

Isn't it better that I use if signal == Signals.CTS: than if signal == "CTS":, or am I missing something?

like image 252
Baz Avatar asked Oct 25 '11 09:10

Baz


2 Answers

Signals.CTS does seem better than "CTS". But Signals is not an enum, it's a class with specific fields. The claim, as I've heard it, is that you don't need a separate enum language construct, as you can do things like you've done in the question, or perhaps:

CTS, DSR, XXX, YYY, ZZZ = range(5)

If you have that in a signals module, it can be imported as used in a similar fashion, e.g., if signal == signals.CTS:. This is used in several modules in the standard library, including the re and os modules.

like image 193
Michael J. Barber Avatar answered Oct 02 '22 10:10

Michael J. Barber


In your exact example, I guess it would be okay to use defined constants, as it would raise an error, when the constant is not found, alas a typo in a string would not.

I guess there is an at least equal solution using object orientation.

BTW: if "CTS": will always be True, since only empty strings are interpreted as False.

like image 32
Constantinius Avatar answered Oct 02 '22 10:10

Constantinius