Can global variable be passed into Python function?
Michael Torrie
torriem at gmail.com
Fri Feb 28 09:49:25 EST 2014
On 02/28/2014 01:46 AM, Ben Finney wrote:
> 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.
Sure. If he replaced the line if self.state is CONNECTED with if
self.state == self.CONNECTED then he is free to change CONNECTED at any
time. So yes, "is" is not necessary here. Equality checking works fine.
More information about the Python-list
mailing list