question of style
steve at REMOVE-THIS-cybersource.com.au
Sat Jul 4 04:04:42 CEST 2009
On Fri, 03 Jul 2009 13:50:12 -0700, Paul Rubin wrote:
> I wouldn't say Python's None is terrible, but the programming style in
> which None is used as a marker for "absent value" is genuinely a source
> of bugs, requiring care when used. Often it's easy to just avoid it and
> all the bugs that come with it.
So you keep saying, but I don't believe it. I've never found this to be a
problem in my own code: a few silly mistakes where I accidentally assign
the result of a function that operates by side-effect:
blist = alist.sort()
or similar, and I haven't done that for years now.
No, wait, I tell I lie... re.search() sometimes bites me, because
sometimes it returns None and sometimes it returns a matchobject and I
don't use re often enough to have good habits with it yet. But that's a
good example of why removing NULL (None, nul, nil, whatever you want to
call it) doesn't lower the number of bugs, it just changes their nature:
if re.search didn't return None, I'd still have trouble with it.
There are three natural approaches to (say) re.search() for dealing with
(1) return a sentinel value like None;
(2) return a matchobject which tests False;
(3) raise an exception.
Here's how you would use them correctly:
# 1 or 2 are handled identically
o = re.search(s)
print "Not found"
# 3 is different
print "Not found"
There's essentially little or no difference in the handling. In all three
cases, if you assume search will always succeed or forget to handle the
failure case, you will write incorrect code:
and get an unexpected exception. The only difference is that the specific
exception will differ between the cases. Remove None from the scenario
doesn't reduce the number of bugs, it just changes their nature.
More information about the Python-list