How do I define custom exceptions across multiple files?

Viewed 870

So I have a Python project that is split across multiple files (to preserve my sanity) and I'm trying to use a custom exception defined in one file in a different file. Basically, I have a.py and b.py. a.py contains a custom exception (customException) that is raised by a function within a.py.

a.py:

class customException(Exception):
   [irrelevant error handling]

def aFunction():
   if [something]:
      raise customException

   return [stuff]

The surrounding code is irrelevant (I hope, otherwise I have a much weirder issue) so I didn't include it. I then import a.py into b.py (they're in the same directory) to use aFunction:

b.py:

import a.py

try:
   var = a.aFunction()
except customException:
   var = [something else]

When I run b.py in a situation where a.py would raise customException, I get the expected a.customException error, but I also get a NameError: name 'customException' is not defined error.

How do I make it so that customException is defined in b.py?

Edit: Paul M.'s solution worked for me just in case anyone else finds this when looking for a solution. Thanks again Paul and everyone else who answered!

1 Answers

You just need to qualify customException by calling it as a.customException from modules where you imported a, like so:

a.py:

class customException(Exception):
   [irrelevant error handling]

def aFunction():
   if [something]:
      raise customException

   return [stuff]

b.py:

import a

try:
   var = a.aFunction()
except a.customException:
   var = [something else]
Related