question of style
steve at REMOVE-THIS-cybersource.com.au
Sun Jul 5 05:04:58 EDT 2009
On Sat, 04 Jul 2009 23:17:21 -0700, Paul Rubin wrote:
> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes:
>> Certain people -- a tiny minority -- keep trying to argue that the
>> ability to say "if obj" for arbitrary objects is somehow a bad thing,
>> and their arguments seem to always boil down to: "If you write code
>> that assumes that only bools have a truth value, then surprising things
>> will happen because all objects have a truth value."
> I'd put it under the general rubric of "explicit is better than
"if x" is explicit. It's difficult to see how a branch could be anything
other than explicit, but never mind.
> The language shouldn't do silly automatic typecasts all over
> the place.
"if x" doesn't involve a typecast. Python doesn't have typecasts, except
possibly for the special case of myobject.__class__ = Another_Class.
If you mean Python shouldn't do silly automatic type conversions all over
the place, I absolutely agree with you! Fortunately, testing the truth
value of an object isn't a silly automatic type conversion.
> 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.
Given an arbitrary object x, how do you know if it's something or
nothing? In general, you can't tell -- but the object can, provided it's
well written. (The conspicuous exception is iterators, but that's a
"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).
Why spend all that effort to find out the length of the object is
59,872,819 only to throw that away? My object knows when it's empty, but
instead you make foolish assumptions about the object and consequently
write wastefully slow code.
> but if I program in a style where I
> like to think I know the type of something when I use it, I'd like the
> interpreter to let me know when I'm wrong instead of proceeding
Oh come on now... that's a silly objection. If you want strongly-typed
variables in Python, say so, don't pretend this is a failure of truth-
testing. 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?
More information about the Python-list