is None or == None ?

Alf P. Steinbach alfps at start.no
Fri Nov 6 10:16:54 EST 2009


* John Machin:
> On Nov 7, 12:35 am, "Alf P. Steinbach" <al... at start.no> wrote:
>> * mk:
>>
>>> Hello,
>>> Some claim that one should test for None using:
>>> if x is None:
>>> ..but the standard equality which is theoretically safer works as well:
>>> if x == None:
>>> So, which one is recommended?
>>
>> As I understand it, 'is' will always work and will always be efficient (it just
>> checks the variable's type),
> 
> It doesn't check the type.
> It doesn't need to. (x is y) is true if x
> and y are the same object. If that is so, then of course (type(x) is
> type(y)) is true, and if not so, their types are irrelevant. "is"
> testing is very efficient in the CPython implementation: addressof(x)
> == addressof(y)

Maybe.

I imagined it wouldn't waste additional space for e.g. (Python 2.x) int values, 
but just use the same space as used for pointer in the case of e.g. string, in 
which case it would have to check the type  --  an integer can very easily have 
the same bitpattern as a pointer residing there.

If you imagine that instead, for an integer variable x it stores the integer 
value in the variable in some other place than ordinarily used for pointer, and 
let the pointer point to that place in the same variable, then without checking 
type the 'is' operator should report false for 'x = 3; y = 3; x is y', but it 
doesn't with my Python installation, so if it doesn't check the type then even 
this half-measure (just somewhat wasteful of space) optimization isn't there.

In short, you're saying that there is an extreme inefficiency with every integer 
dynamically allocated /plus/, upon production of an integer by e.g. + or *, 
inefficiently finding the previously allocated integer of that value and 
pointing there, sort of piling inefficiency on top of inefficiency, which is 
absurd but I have seen absurd things before so it's not completely unbelievable.

I hope someone else can comment on these implications of your statement.


Cheers,

- Alf



More information about the Python-list mailing list