Prev: 2to3 on Mac - unknown encoding: mbcs
Next: safely returning objects from a Process to the parent through aQueue()
From: mk on 6 Nov 2009 08:20 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? Can there be two None objects in interpreter's memory? Is testing for identity of some variable with None safe? Does language guarantee that? Or is it just property of implementation? Regards, mk
From: Stefan Behnel on 6 Nov 2009 08:33 mk, 06.11.2009 14:20: > Some claim that one should test for None using: > > if x is None: Which is the correct and safe way of doing it. > ..but the standard equality which is theoretically safer works as well: > > if x == None: Absolutely not safe, think of class Test(object): def __eq__(self, other): return other == None print Test() == None, Test() is None Stefan
From: Alf P. Steinbach on 6 Nov 2009 08:35 * 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? > > Can there be two None objects in interpreter's memory? Is testing for > identity of some variable with None safe? Does language guarantee that? > Or is it just property of implementation? As I understand it, 'is' will always work and will always be efficient (it just checks the variable's type), while '==' can depend on the implementation of equality checking for the other operand's class. Cheers & hth., - Alf
From: John Machin on 6 Nov 2009 09:09 On Nov 7, 12:35 am, "Alf P. Steinbach" <al...(a)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)
From: Marco Mariani on 6 Nov 2009 09:13
Alf P. Steinbach wrote: > As I understand it, 'is' will always work and will always be efficient > (it just checks the variable's type), while '==' can depend on the > implementation of equality checking for the other operand's class. "== None" makes sense, for instance, in the context of the SQLAlchemy sql construction layer, where the underlying machinery defines __eq__() / __ne__() and generates the appropriate 'IS NULL' SQL code when appropriate. |