converting from perl: variable sized unpack
quinn at yak.ugcs.caltech.edu
Wed Jul 18 17:19:54 EDT 2001
On Wed, 18 Jul 2001 13:20:54 +0100, phil hunt <philh at comuno.freeserve.co.uk>
>>> This goes for lots of things; IMO if you
>>> access a list or dictionary with a non-existant index it should
>>> return a value such as None, instead of raising an exception.
>>Sometimes. It's convenient in CGI to have tags default to '' if missing.
>>But you can't find a one-size-fits all solution. For some applications,
>>None and '' are legitimate values, and must be distinguished from
>>"key not found". Thus, why Python offers both dict.get('x', DEFAULT)
>>as well as dict['better be there or KeyError'].
>No, because on the odd occasions that you want an exception you can
>always throw one manually.
>Here, I'm assuming that usually you don't want one -- perhaps this
>is jsut my idiosyncratic programming style and most people vare different
It's not just you, but I don't agree, and it's not just me either.
NameErrors, KeyErrors, and IndexErrors have saved me many times. One of the
things I didn't like about perl is how it magically created values on
reference, and then I had to go hunt down the bad reference that created it.
And I often store None in dicts and lists. It would be weird if d.has_key(x)
could be true or false while d[x] always evaluated to None. That means that
d[x] is implicitly creating a None when d.has_key(x) is false, but not when
it's true (python's None is a normal value, not a magic "nothing"
I like all bad references to be errors, always, not "press on and hope for the
best" or "depends on what declarations were made" or "depends on what kind of
reference it is" (as in ruby).
Perl has undef, and lua has nil, and in both those languages saying 'x = nil'
is equavalent to unbinding `x' (I think that's true for perl, don't remember).
If python's None were to be consistent we should remove NameError and del and
have all unbound names evaluate to None. Then people would request perl-like
'use strict' hacks to turn it off.
And lastly, and most importantly, that's the way the language works. Some
languages may work differently, but many languages also work this way. Since
obviously no one agrees, there is no "should". And there has to be a really
clear "should" to justify breaking code for it.
For the circumstances when it's handy to have a 'default value' dict or list
that never raises, it's easy to subclass UserDict.
More information about the Python-list