easy question on parsing python: "is not None"

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Aug 6 10:32:00 CEST 2010

Richard D. Moores a écrit :
> On Thu, Aug 5, 2010 at 16:15, Rhodri James <rhodri at wildebst.demon.co.uk> wrote:
>> On Thu, 05 Aug 2010 17:07:53 +0100, wheres pythonmonks
>> <wherespythonmonks at gmail.com> wrote:
>> You're not testing for equivalence there, you're testing for identity.  "is"
>> and "is not" test whether the two objects concerned are (or are not) the
>> same object.  Two objects can have the same value, but be different objects.
>>  The interpreter can fool you by caching and reusing objects which have the
>> same value when it happens to know about it, in particular for small
>> integers, but this is just a happy accident of the implementation and in no
>> way guaranteed by the language.  For example:
>>>>> "spam, eggs, chips and spam" is "spam, eggs, chips and spam"
>> True
>>>>> a = "spam, eggs, chips and spam"
>>>>> b = "spam, eggs, chips and spam"
>>>>> a is b
>> False
>>>>> a == b
>> True
> I'm wondering if there isn't considerable predictability to that
> "happy accident".

There is, indeed, but that's really implementation details.

> Note how 1 'word' is treated versus 2:
>>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk'
>>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkjshadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk'
>>>> x is y
> True
>>>> x = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk'
>>>> y = 'alksjdhflkajshdflkajhdflkjahsdflkj hadflkjhsadlfkjhaslkdjfhslkadhflkjshdflkjshdflkjshdfk'
>>>> x is y
> False

CPython caches strings that happen to be valid Python identifiers. But 
once again, this is an implementation-specific optimization.

More information about the Python-list mailing list