question of style

Paul Rubin http
Sun Jul 5 06:08:16 EDT 2009


Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
> > Yes, it saves a few keystrokes to say "if x:" instead of "if
> > len(x)==0:" or even "if bool(x):", 
> 
> It's not about saving keystrokes -- that's a furphy. It's about 
> encapsulation. Objects are in a better position to recognise when they 
> are "something" (true) or "nothing" (false) than you are.

I don't know what a furphy is, but I don't accept that "somethingness"
vs. "nothingness" is the same distinction as truth vs falsehood.  True
and False are values in a specific datatype (namely bool), not
abstract qualities of arbitrary data structures.  The idea that the
"if" statement selects between "somethingness" and "nothingness"
rather than between True and False is a bogus re-imagining of the
traditional function of an "if" statement and has been an endless
source of bugs in Python code.  Look how much confusion it causes here
in the newsgroup all the time.

> "if len(x) == 0" is wasteful. Perhaps I've passed you a list-like 
> iterable instead of a list, and calculating the actual length is O(N). 

That doesn't happen in any of Python's built-in container types.  I
could see some value to having a generic "is_empty" predicate on
containers though, to deal with this situation.  Your iterable could
support that predicate.  In fact maybe all iterables should support
that predicate.  They don't (and can't) all support "len".

> If you write len(x)==0 Python doesn't complain if x is a dict
> instead of the list you were expecting. Why is it acceptable to
> duck-type len(x) but not truth-testing?

I haven't seen the amount of bugs coming from generic "len" as from
something-vs-nothing confusion.



More information about the Python-list mailing list