Can global variable be passed into Python function?

Marko Rauhamaa marko at pacujo.net
Fri Feb 28 08:43:58 CET 2014


Chris Angelico <rosuav at gmail.com>:

> Simple rule of thumb: Never use 'is' with strings or ints. They're
> immutable, their identities should be their values. Playing with 'is'
> will only confuse you, unless you're specifically going for
> introspection and such.

Here's a use case for "is" with strings (or ints):

   class Connection:
       IDLE = "IDLE"
       CONNECTING = "CONNECTING"
       CONNECTED = "CONNECTED"
       DISCONNECTING = "DISCONNECTING"
       DISCONNECTED = "DISCONNECTED"

       def __init__(self):
           self.state = IDLE

       def connect(self, address):
           ...
           self.state = CONNECTING
           ...

       def disconnect(self):
           ...
           if self.state is CONNECTED:
               ...

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))


Marko



More information about the Python-list mailing list