Exception problems

Greg Ewing see_reply_address at something.invalid
Wed Dec 4 21:24:24 EST 2002


Richard Jones wrote:

> The exception "name" also 
> differs - in a.py as-a-script, it's "__main__.FooExc" and in a.py as-a-module 
> and b.py it's "a.FooExc".
> 
> Is this a bug or a feature?


I'd call it a "well-known misfeature" (well-known to
those that have been bitten by it before, anyway).

When you invoke a .py file as a script, it gets
turned into a module called __main__, regardless
of the name of the file it came from.

If the script then, directly or indirectly,
imports itself by name, a *second*
module is created and initialised from the
same .py file.

So in your case you're getting two copies
of your a.py loaded, with different instances
of FooExc in them. Since exceptions are matched
by identity, this is a Bad Thing.

The workaround is to create a third .py file
which simply imports a.py, and use that as
your script.

In general, whenever you have a Python program
split over more than one .py file, make sure
none of them ever import the "main" one.

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg




More information about the Python-list mailing list