On 5/21/2011 7:46 AM John J Lee said...
Gregory Ewing<greg.ew...@canterbury.ac.nz> writes:
Hans Georg Schaathun wrote:
0 is a number as real and existent as any other,
one would think that the empty list is also as real and existent as
any other list.
0 does have some special properties, though, such as
being the additive identity and not having a multiplicative
inverse. Adding falseness as another special property isn't
too much of a stretch and turns out to be useful.
Likewise, it's useful to treat empty containers as having
a similar special property, since they're often a base or
terminating case in algorithms.
It's especially useful in a dynamic language where any
additional operations such as finding the length or
comparing with zero has a run-time cost.
Yes, you have to learn it, but it's a small thing to
learn with a considerable payoff.
(apologies if somebody already bikeshedded this argument in this thread)
In the absence of an explicit interface declaration (have any standards
emerged for that in Python 3, BTW?), the use of len() does give you some
information about the interface, which sometimes makes it easier to
change the function.
I'm sure you fully understand this, but I'll spell it out. Consider
this function:
def xyzzy(x):
if x:
print "yes"
Let's say I've read the function, and I've seen this call site:
xyzzy(["spam", "eggs"])
Now I want to change xyzzy:
def xyzzy(x):
if x:
print "probably"
if len(x) == 1:
print "definitely"
But there may be many call sites. Perhaps xyzzy even implements part of
a poorly-documented external API. So can x be None? There's no way to
know short of checking all call sites, which may be impossible. It may
not even be feasible to check the *only* call site, if you're
implementing somebody else's poorly documented closed-source API (a
situation I came across at work only yesterday, when that situation
resulted in a bug report). If it's written this way, it's clear that it
can't be None:
qualified: "...without having been trapped or crashing" so if I found
this function in running code it would be clear to me that, given that
the app is running and hasn't been crashing, either it hasn't yet been
None, or the code isn't accessed at all.
Emile
def xyzzy(x):
if len(x) != 0:
print "yes"
John
--
http://mail.python.org/mailman/listinfo/python-list