python for this C: "if ((a = b(c)) != NULL)"

Alex Martelli aleax at aleax.it
Tue May 14 09:06:47 EDT 2002


David Carson wrote:
        ...
> So, I'll ask again: How do I do the equivalent in Python so that it is
> both clear and concise?

"Clear" is in the eye of the beholder.  Some will detest you if you use 
this, or even detest me for pointing it out, but...:

if [a for a in [b(c)] if a is not None]:
        whatever(a)

This abuse of list comprehensions is 'the' way, in Python 2.0, to
bind a variable name within an _expression_ -- normally, Python
rebinds variables only in _statements_, but list comprehensions
let you escape this stricture if you really can't live with it.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66061
gives another alternative, which I find preferable when I do have
to transliterate C, C++ or Perl code using assign-and-test idioms
into Python without altering structure -- but, it does require a bit
of infrastructure (4 lines' worth of class definition) as it does not
rebind a name but rather 'assigns' the value through the method
of a class instance.  The list-comprehension-abuse works entirely
within Python and requires no supporting infrastructure.

But its clarity may not be sufficient to make it worth using.


Alex




More information about the Python-list mailing list