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?
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With