开发者

Python: Organization of user-defined exceptions in a complete project

开发者 https://www.devze.com 2023-01-25 06:45 出处:网络
I have some questions about user-defined exceptions in Python and how they should be organized in a complete project.

I have some questions about user-defined exceptions in Python and how they should be organized in a complete project.

I have a fairly complex python project with some sub-packages that has the following structure (__init__.py omitted):

/docs (Documentation)
/apidocs (generated API documentation)
/askindex (my application package)
    /test (Unit tests directory)
        test_utils.py
        ... (more tests)
    /workers (various worker classes)
        communicators.py
        processes.py
        threads.py
        utils.py
    main.py (contains the starting point)
    data_objects.py (various objects used all around the application)
    settings.py (settings of the application)
README.txt

I would like to implement my own Exception to use them in the modules of the 'workers' package for specific errors.

Where should I place these exceptions ? I know that I should have my own base exception which subclasses the standard Exception class and subclass it for my other exceptions. Should I create a new 'exceptions' module under 'workers' ? Put exception classes in the module in which they're raised ? In this case, where should I put my base class ? Is my application structure approp开发者_JAVA百科riated ?

I am new to exceptions in Python, so please excuse me if the answer is obvious...


In general I've found with my own work that when I want a custom type of exception, it's specific to a particular module or package. If it's relevant to a module, I put it just in that module. I haven't yet found a case where it would be neater to have a module or package dedicated to exceptions.

Examples: if I have a jester module, with a class Juggler in it with a method juggle which can raise a DroppedBall (cue throwing rotten tomatoes or similar), the DroppedBall would be in the jester module. Then the crowd.Person instances could try watching the juggler and except jester.DroppedBall.

If I had a package food, with various modules in it, fruit, vegetable, etc. which all have an eat method (inherited from food.Foodstuff, doubtless), they might be able to raise a RottenException, which would naturally belong in the root of the food package: __init__.py.

0

精彩评论

暂无评论...
验证码 换一张
取 消