Exceptions and modules / namespaces question

Cliff Wells logiplexsoftware at earthlink.net
Thu Mar 28 19:17:31 EST 2002


On Thu, 28 Mar 2002 15:57:15 -0800
Emile van Sebille wrote:

> Preston Landers
> > The problem, in a nutshell, is that I can't seem to catch an exception
> > in the same module it was defined in if the function that raised the
> > exception is in a different module, because of naming issues.
> >
> 
> It seems to me that you have a __main__ vs module1 issue.  When module2
> imports module1, it gets a new copy, not __main__.
> 
> > -------module2.py:
> >
> > import module1
> >
> > def raise_foo_exception():
> >    raise module1.FooException("HELLO")
> >
> > -------module1.py:
> >
> > import exceptions, sys
> >
> > class FooException(exceptions.Exception):
> >    pass
> >
> > def main():
> >
> >    try:
> >        import module2
> 
> if you import module1 here
> 
> 
> >        module2.raise_foo_exception()
> >    except FooException, e:
> 
> then except module1.FooException
> 
> it may work.  Better perhaps to define your exceptions in a separate
> module and import it into both.

I failed to notice that his main() function was also in module1 (replying
without reading is a specialty of mine ;)  Maybe this will make the
namespace issue clearer

    except module2.module1.FooException, e:

works, but it would obviously be cleaner if both the main program and
module2 imported module1.  /Then/ he could simply use module1.FooException.

Regards,

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308




More information about the Python-list mailing list