Can global variable be passed into Python function?

Ben Finney ben+python at benfinney.id.au
Fri Feb 28 03:46:48 EST 2014


Steven D'Aprano <steve at pearwood.info> writes:

> On Fri, 28 Feb 2014 09:43:58 +0200, Marko Rauhamaa wrote:
> >    class Connection:
> >        IDLE = "IDLE"
> [...]
> >        CONNECTED = "CONNECTED"
> [...]
> >        def disconnect(self):
> >            ...
> >            if self.state is CONNECTED:
> >                ...
>
> Why do you care that the state is *that specific* string, rather than
> any old string with the value "CONNECTED"?

I can think of a reason:

* When you publish the API for the ‘Connection’ class,

* and another party writes code that sets ‘state’ to a string with the
  value ‘"CONNECTED"’,

* and you implemented the check as ‘self.state == "CONNECTED"’,

* and their code works with your class and it goes into production,

* you're then not able to change the expected value without breaking
  that party's code.

On the other hand, if the only value which will work is the one which
the caller gets via ‘Connection.CONNECTED’, then you can change the
implementation later without breaking existing code.


There are two reasons why I think this is *still* not a justification
for using ‘is’ with string values:

First reason: This is better done by making it clear the value is an
arbitrary object that won't be compared for equality. Just use
‘object()’ to creeate each value and be done with it. That's a hack, but
it's better than pretending you'll use the string as a string of text
and then breaking that expectation.

Second reason: This use case is a primary motivation for the Enum
pattern. The Enum pattern is implemented in the standard-library ‘enum’
module, now in Python 3.4 <URL:http://python.org/dev/peps/pep-0435/>.

So, I think Marko's use case is not a justification for comparing string
values with ‘is’.

-- 
 \        “Pinky, are you pondering what I'm pondering?” “Wuh, I think |
  `\   so, Brain, but if we didn't have ears, we'd look like weasels.” |
_o__)                                           —_Pinky and The Brain_ |
Ben Finney




More information about the Python-list mailing list