spliting on ":"

Peter Hansen peter at engcorp.com
Sat Mar 4 19:22:00 EST 2006


Cyril Bazin wrote:
> Ok, ok, there was a mistake in the code.
> (Of course, it was done on prupose in order to verify if everybody is 
> aware ;-)
> I don't know why it is preferable to compare an object to the object 
> "None" using "is not".
> "==" is, IMHO, more simple. Simple is better than complex.. So I use "==".

The archives could tell you more, but basically on is usually interested 
in *identity* with a singleton object (None), not in whether the object 
on is examining happens to compare equal.  A custom object could be 
designed to compare equal to None in certain cases, even though it *is 
not* None, leading to the "== None" approach being defective code.

In the specific code in question, it won't make any differences, but I 
pointed it out to help folks who don't know this to start developing the 
safer habit, which is always to use "is" and "is not" with None (or, 
generally, with other singletons).

> The correct program is:
> 
> import urllib2
> for line in open("fileName.txt"):
>     addr, port  = urllib2.splitport (line)
>     print (port == None) and '' or port

Nope, sorry... the point is that the "and/or" pseudo-ternary operator is 
inherently flawed if the operand after "and" evaluates False.  Check 
this out:

 >>> port = None
 >>> print (port == None) and '' or port
None
 >>> print (port != None) and '' or port
None

and even:

 >>> print (port is None) and '' or port
None

So the bug isn't in using "!=" instead of "==", or using equality 
instead of identity comparison, it is in trying to use the and/or 
expression for a purpose it wasn't intended for.

> or
> 
> import urllib2
> for line in open("fileName.txt"):
>     addr, port  = urllib2.splitport(line)
>     if port == None:
>         print ''
>     else:
>         print port

That should work nicely... and it's more readable too!

Note that in Python 2.5 you should be able to write this as

     print '' if port is None else port
or  print '' if (port is None) else port

but it's quite arguable whether that is better than the simple if/else 
statement in this case.

-Peter




More information about the Python-list mailing list