[Tutor] A Python idiom that I don't get

Kent Johnson kent37 at tds.net
Wed Apr 26 04:43:25 CEST 2006

Don Taylor wrote:
> I am trying to get some existing CPython 2.4 code working under Jython 
> (2.1) and I am puzzled by a line in the following function.  It seems to 
> be a Python 2.4 idiom that is opaque to me.
> The line is:
>      prefix = os.path.commonprefix(filter( bool, lines ))
> and I don't understand what that 'bool' is doing.  Or rather, I think 
> that I see what it is doing, but I am not sure - and I don't much like it.
> filter is the built-in filter and it requires a callable returning a 
> bool as the first argument.  It seems that 'bool' without arguments is a 
> callable that always evaluates to True (or at least non-zero) so this 
> 'bool' always returns True.  Is this really true (sic) by intention or 
> is it just an implemenation artifact?

No, bool() doesn't always return true, it returns true for arguments 
that would evaluate to true in a boolean context, and false otherwise.

In [2]: bool(0)
Out[2]: False

In [3]: bool(1)
Out[3]: True

In [4]: bool([])
Out[4]: False

In [5]: bool(42)
Out[5]: True
> I tried replacing 'bool' with 'True' but that won't work because True is 
> not callable.
> I replaced 'bool' with 'lambda True: True' as in:
>      prefix = os.path.commonprefix(filter( lambda True: True, lines ))
> and that does seem to work - and pass its unit tests.

This works but it isn't doing what you think it is.
lambda True: True
is the same as
lambda x: x

i.e. it is just an identity function.
> Have I got this right and can I replace 'bool' with the lambda expression?
> Or is there a clearer way to do this?

Try filter(None, lines) or use a list comprehension:
[ line for line in lines if line ]


More information about the Tutor mailing list