[Answered ]-Custom Python exception with different include paths

1👍

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.

import exceptions
l=[]
try:
    l[1]
except exceptions.IndexError,e:
    print e

try:
    l[1]
except IndexError,e:
    print e

both catch the same exception

you can even assign it to a new name, though not recommended usually

import os
os.myerror = exceptions.IndexError
try:
    l[1]
except os.myerror,e:
    print e

1👍

“If not, what would be best practices to avoid these name clashes?”

That depends entirely on why they happen. In a normal installation, you can not import from both application.exceptions and somepath.application.exceptions, unless the first case is a relative path from within the module somepath. And in that case Python will understand that the modules are the same, and you won’t have a problem.

You are unclear on if you really have a problem or if it’s theory. If you do have a problem, I’d guess that there is something fishy with your PYTHONPATH. Maybe both a directory and it’s subdirectory is in the PATH?

0👍

Even if the same module is imported several times and in different ways, the CustomException class is still the same object, so it doesn’t matter how you refer to it.

👤balpha

0👍

I don’t know if there is a way to handle this inclusion path issue.
My suggestion would be to use the ‘as’ keyword in your import

Something like:

import some.application.exceptions as my_exceptions

or

import application.exceptions as my_exceptions

👤luc

Leave a comment