Update: This is, as I was told, no principle Python related problem, but seems to be more specific. See below for more explanations to my problem.
I have a custom exception (let’s call it CustomException), that lives in a file named exceptions.py. Now imagine, that I can import this file via two paths:
import application.exceptions
or
import some.application.exceptions
with the same result. Furthermore I have no control over which way the module is imported in other modules.
Now to show my problem: Assume that the function do_something comes from another module that imports exceptions.py in a way I don’t know. If I do this:
import application.exceptions
try:
do_something ()
except application.exceptions.CustomException:
catch_me ()
it might work or not, depending on how the sub-module imported exceptions.py (which I do not know).
Question: Is there a way to circumvent this problem, i.e., a name for the exception that will always be understood regardless of inclusion path? If not, what would be best practices to avoid these name clashes?
Cheers,
Update
It is a Django app. some would be the name of the Django ‘project’, application the name of one Django app. My code with the try..except clause sits in another app, frontend, and lives there as a view in a file some/frontend/views.py.
The PYTHONPATH is clean, that is, from my project only /path/to/project is in the path. In the frontend/views.py I import the exceptions.py via import application.exceptions, which seems to work. (Now, in retrospective, I don’t know exactly, why it works…)
The exception is raised in the exceptions.py file itself.
Update 2
It might be interesting for some readers, that I finally found the place, where imports went wrong.
The sys.path didn’t show any suspect irregularities. My Django project lay in /var/www/django/project. I had installed the apps app1 and app2, but noted them in the settings.py as
INSTALLED_APPS = [
'project.app1',
'project.app2',
]
The additional project. was the culprit for messing up sys.modules. Rewriting the settings to
INSTALLED_APPS = [
'app1',
'app2',
]
solved the problem.
Why that would be a problem? exception would me matched based on class type and it would be same however it is imported e.g.
both catch the same exception
you can even assign it to a new name, though not recommended usually