When to use try and except?

Carl Banks pavlovevidence at gmail.com
Sat Aug 30 21:32:41 CEST 2008


On Aug 30, 2:03 am, Fredrik Lundh <fred... at pythonware.com> wrote:
> Carl Banks wrote:
> > I wouldn't say that the possibility of EAFP in Python makes it
> > obsolute to use LBYL.
>
> when using CPython, EAFP at the Python level always involve LBYL at the
> C level.

I don't think that's true.  For example, here is the code that
actually opens a file within the open() function:

        if (NULL == f->f_fp && NULL != name) {
                Py_BEGIN_ALLOW_THREADS
                f->f_fp = fopen(name, newmode);
                Py_END_ALLOW_THREADS
        }

        if (f->f_fp == NULL) {

Clearly it tries to open the file, and handles the error if it fails.
EAFP, even though it wasn't using an exception.

Of course, underneath fopen there could be LBYL somewhere, but that's
at either the the system library level or the OS level.  Perhaps it's
part of what you meant by C level, since those guys probably are
written in C.

But then I still don't think we call say LBYP *always* occurs at the C
level, since in some cases the library and system calls that Python
wraps rely on processor exceptions and stuff like that.  Which means
any LBYPing is going on inside the CPU, so it's at the hardware level.

I realize all of this is tangential to your point.


> and it should be obvious to any programmer that checking for
> the same thing twice is quite often a waste of time and resources.

Well if there's a section where performance is important I'd use
EAFP.  It's no big deal.


Carl Banks



More information about the Python-list mailing list