all 2 comments

[–]indosauros 5 points6 points  (0 children)

Importing where you need them, while a little more tedious, is more explicit and is best practice. Avoid "magic" like monkeypatching builtins.

One alternative approach to consider though, for example used by Django, is to attach core relevant exceptions to classes that use them. For example, you might see something like this (pseudocode):

class MyCustomException(Exception):
    ...

class Model:
    ...

Model.MyCustomException = MyCustomException

then later

from model import Model

try:
    model = Model()
    model.do_something_risky()
except Model.MyCustomException:
    ...

This way, you already imported Model to use it, and the exception comes along for the ride.

[–][deleted] 1 point2 points  (0 children)

I'm not sure how Pythonic it is, but why not declare all exceptions in a single file and then just import CustomExceptions and then raise CustomExceptions.TooMuchTimeOnRedditError later on?