converting from perl: variable sized unpack

Alex Martelli aleaxit at yahoo.com
Wed Jul 18 17:48:01 EDT 2001


"phil hunt" <philh at comuno.freeserve.co.uk> wrote in message
news:slrn9lavp6.v3.philh at comuno.freeserve.co.uk...
    ...
>    if not myCollection.hasIndex(x): raise Exception
>
> (Note that hasIndex() should equally work for dictionaries as well
> as sequence-collections (strings, tuples, lists, etc). IMO it is
> an unnecessary non-orthogonality of the present python that it doesn't
> do this)

It's quite orthogonal if you think of exceptions as the MAIN way
to communicate the missing index case:

def hasindex(myCollection, x):
    try:  myCollection[x]
    except LookupError: return 0
    else: return 1

LookupError is the common base class of IndexError, raised by
sequences, and KeyError, raised by mappings.


> No, because on the odd occasions that you want an exception you can
> always throw one manually.

And viceversa, if the odd occasions are those in which you
want to SUPPRESS the exception, you can easily try/except it.

> Here, I'm assuming that usually you don't want one -- perhaps this
> is jsut my idiosyncratic programming style and most people vare different
> here. Comments?

I think that most languages supporting exceptions are hinged
to using them only for exceptional cases, so it's clearly going
to be common for people with such backgrounds to find that
style the 'usual' one -- but I also think that best Pythonic style
is different, and very oriented to "it's easier to ask forgiveness
than permission", and to rather free use of exceptions.


Alex






More information about the Python-list mailing list