Exceptions and modules

Duncan Booth duncan at NOSPAMrcp.co.uk
Fri Jul 4 16:45:37 CEST 2003

westernsam at hotmail.com (sam) wrote in 
news:292c8da4.0307040627.59acda19 at posting.google.com:

> So the Exception isn't recognised even though it has the same
> namespace and name as the exception defined in the module. I have to
> uncomment the 7th line to get my example to behave as I would like it
> to.
> Is this a bug/feature? Is there any reason why it shouldn't work the
> way I expect it to?

It's a feature, and it probably ought to be in the FAQ in some form.

When you run 'python module1.py' the code in the source file module1.py is 
compiled into a module called __main__. That means that the line:

    except MyException, err:

is actually short for:

    except __main__.MyException, err:

When module2 imports module1 the code is recompiled into a new module. Same 
source code, but otherwise no relation. You then raise module1.MyException 
which doesn't match __main__.MyException.

Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list