Creating a variable of a specific type

Jp Calderone exarkun at intarweb.us
Thu Feb 5 15:31:40 CET 2004


On Thu, Feb 05, 2004 at 08:54:29AM -0500, Aahz wrote:
> In article <bvtei9$10enm4$1 at ID-111250.news.uni-berlin.de>,
> Diez B. Roggisch <nospam-deets at web.de> wrote:
> >
> >Now back to your problem: I don't know right from my head what socket
> >requires as inet-type, but I guess its a tuple of some sort. You don't need
> >to declare a variable for that - just use it. If you need to check for a
> >symbol not beeing initialized, simply use None as value, like here:
> >
> >address = None
> >if address:
> >  do_something(address)
> >
> >None is considered false. You might be more explicit, by using
> >
> >if address == None:
> >
> >but thats a matter of taste (to me, at least...)
> 
> No, that's not a matter of taste, it's a matter of incorrect coding.
> Using ``==`` calls a method on address, which could return true even if
> address isn't None.  Much better to use ``is``, which is guaranteed to
> return true only if address really *is* None.
> 
> Note that in the absence of special methods for comparison, all Python
> objects are true, so your original formulation is especially appropriate.

  Just as using "==" calls a method on address, which could return true even
if address isn't None, calling bool() with address may return false, even if
address isn't None!  "if address:" may work in some cases, but it will
return incorrect results when address has been initialized to another false
value ([] is especially common, I find), when it is initalized to a class
defining __nonzero__/__len__ in certainly ways, and in some unfortunate
cases it may even raise an exception (eg, cgi.FieldStorage).

  Jp




More information about the Python-list mailing list