Python Strings

Alex Martelli aleaxit at yahoo.com
Wed Sep 6 23:05:12 CEST 2000


"Quinn Dunkan" <quinn at cruzeiro.ugcs.caltech.edu> wrote in message
news:slrn8rd4v2.7mq.quinn at cruzeiro.ugcs.caltech.edu...
> On Wed, 6 Sep 2000 14:16:19 +0200, Alex Martelli <aleaxit at yahoo.com>
wrote:
> >do.  In Python, you can try/except, catch the resulting
> >TypeError, and even, I think, parse the message "not
> >enough arguments; expected 1, got 0" to get a hint
> >about how many args you should supply (alas, it's
>
> It would be easier to check f.func_code.co_argcount

Oh really?

>>> somefun=callable
>>> somefun.func_code.co_argcount
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: func_code
>>>

See how far "checking f.func_code.co_argcount" gets
you in the general case...?

While...:

>>> try: somefun()
... except TypeError,x: print x
...
callable requires exactly 1 argument; 0 given
>>>


So, do you think it's "easier" to check attributes
that might or might not be there -- or are you
using "would be" in the hypothetical counterfactual
sense, as in, "it woud be easier, if it worked for
the general case, pity that it just doesn't..."?


Plus: co_argcount may well be >0, but you can
still call the function without arguments as long
as all parameters have a default value.  You must
check for that, too.  And are you *SURE* there
aren't another half a dozen issues that just might
come up...?


Remember: *it's easier to ask forgiveness than
permission*.  Trying to "proactively check" that
all prerequisites are satisfied, before attempting
a certain operation, is generally far too much
trouble -- if you can even do it at all in the
general case, that is.  Thinking that this is _easier_
than a try/except block is a misconception that
may severely cramp one's programming style.

Some people have issues with try/except on
stylistic grounds, based on the fact that any
"exception" should be something that only
happens _exeptionally_, i.e., very rarely.  I see
how this concept applies in certain other
programming languages -- but, in Python, it's
not really applicable at all.  For example, any time
you code a perfectly normal for/in loop in Python,
you know that it *will* be terminated when an
exception is raised (unless a 'break' or 'return'
happens to end it sooner -- not the most common
occurrence in most people's use of for/in).  So,
far from being 'exceptional', exceptions in Python
are actually pretty common.  No real reason to
eschew them, then, if and when relying on them
can help you simplify your code...!


Alex






More information about the Python-list mailing list