On Fri, Feb 28, 2014 at 6:43 PM, Marko Rauhamaa <ma...@pacujo.net> wrote: > Here's a use case for "is" with strings (or ints): > > class Connection: > IDLE = "IDLE" > CONNECTING = "CONNECTING" > CONNECTED = "CONNECTED" > DISCONNECTING = "DISCONNECTING" > DISCONNECTED = "DISCONNECTED" > > The state objects could have been defined like this: > > IDLE = object() > CONNECTING = object() > CONNECTED = object() > DISCONNECTING = object() > DISCONNECTED = object() > > However, strings have the advantage in troubleshooting: > > sys.stderr.write("state = {}\n".format(self.state))
As Ben said, strong use-case for enums (either migrate to 3.4, or check PyPI). But here's an alternative that uses object identity safely. (Remember, all it takes is a bit of string interning and two equal strings could become identical.) class enum: def __init__(self, desc): self.desc = desc def __repr__(self): return self.desc IDLE = enum("IDLE") CONNECTING = enum("CONNECTING") CONNECTED = enum("CONNECTED") DISCONNECTING = enum("DISCONNECTING") DISCONNECTED = enum("DISCONNECTED") Now object identity is the right way to do things, and you can still do the formatting just like you say; plus there's no way to accidentally get something that seems to work. Of course, the real enum type is far more sophisticated than that, but the concept is the same. It's an object. ChrisA -- https://mail.python.org/mailman/listinfo/python-list