Difference between 'is' and '=='
Dan Sommers
me at privacy.net
Mon Mar 27 21:05:54 EST 2006
On Mon, 27 Mar 2006 11:08:36 -0300,
Felipe Almeida Lessa <felipe.lessa at gmail.com> wrote:
> Em Seg, 2006-03-27 às 08:23 -0500, Dan Sommers escreveu:
>> On Mon, 27 Mar 2006 14:52:46 +0200,
>> Joel Hedlund <joel.hedlund at gmail.com> wrote:
>>
>> > ... According to PEP8 (python programming style guidelines) you should
>> > use 'is' when comparing to singletons like None. I take this to also
>> > include constants and such ...
>>
>> This does *not* also mean constants and such:
>>
>> Python 2.4.2 (#1, Feb 22 2006, 08:02:53)
>> [GCC 4.0.1 (Apple Computer, Inc. build 5247)] on darwin
>> Type "help", "copyright", "credits" or "license" for more information.
>> >>> a = 123456789
>> >>> a == 123456789
>> True
>> >>> a is 123456789
>> False
>> >>>
> Not those kind of constants, but this one:
> Python 2.4.2 (#2, Nov 20 2005, 17:04:48)
> [GCC 4.0.3 20051111 (prerelease) (Debian 4.0.2-4)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> CONST = 123456789
>>>> a = CONST
>>>> a == CONST
> True
>>>> a is CONST
> True
>>>>
That's a little misleading, and goes back to the questions of "what is
assignment in Python?" and "What does it mean for an object to be
mutable?"
The line "a = CONST" simply gives CONST a new name. After that, "a is
CONST" will be True no matter what CONST was. Under some circumstances,
I can even change CONST, and "a is CONST" will *still* be True.
>>> CONST = range(22)
>>> a = CONST
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
>>> a is CONST
True
>>> CONST[12] = 'foo'
>>> a is CONST
True
>>>
Right off the top of my head, I can't think of a way to make "a = b; a
is b" return False.
Regards,
Dan
--
Dan Sommers
<http://www.tombstonezero.net/dan/>
"I wish people would die in alphabetical order." -- My wife, the genealogist
More information about the Python-list
mailing list