2

I am reading the python doc and it mentions that

Two exception classes that are not related via subclassing are never equivalent, even if they have the same name.

I'm not sure why it is possible to have two exception classes with the same name but different subclassing. Shouldn't some kind of error/warning be generated in that case?

1
  • A linter will probably complain if you shadow an existing name, but there's no reason for it to be an error as far as the interpreter is concerned - you might want to shadow it. Commented Oct 11, 2016 at 21:16

1 Answer 1

3

Exceptions are just specific types of classes. Class names are simply what they are defined as. Forbidding classes to have the same name would brake lots of coding schemes. One such example actually works on exceptions: programs that need to be backwards compatible with python2.6 will often override subprocess.CalledProcessError to conform to the python2.7/3.X interface.

How can you have two exceptions of the same name but different subclassing? You are for example free to do the following:

class ExceptoPatronum(KeyError):
    pass

KExcept = ExceptoPatronum

class ExceptoPatronum(OSError):
    pass

OExcept = ExceptoPatronum

The classes are named the same but neither equal nor instances of each other:

print(KExcept.__name__)
print(OExcept.__name__)
print(KExcept == OExcept, KExcept is OExcept)

This is a (contrived) example that runs even with just one file. However, imagine you have two separate modules which each define their own custom class with the same name, let's say ResourceUnavailable.

As long as they are separate, why should users be warned about such internals? If another module relies on both, would you require it to replace them? It would be a nightmare to track such name collisions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.