How to organize a Python module with many constants and exceptions?

I am writing a Python module that has only about 20 interesting types and global methods, but many constants and exceptions (about 70 constants for locales, 60 constants for encodings, 20 formatting attributes, more than 200 exceptions, etc. on). As a result, help() on this module produces about 16,000 lines of text and is dotted with almost identical descriptions of each exception. Constants are not so demanding, but they are still hard to navigate.

What would be the pythonic way to organize such a module? Just leave it as it is and rely on other documentation? Move constants to separate dicts? Into submodules? Add them as class level constants, where appropriate?

Note that this is a C extension, so I cannot easily add a real submodule here. I heard that sys.modules does not actually check if the object has a module, so you can add dictionaries there; that way, I could create mymodule.locales , mymodule.encoding and mymodule.exceptions and add them to sys.modules when my module is imported. Will this be a good idea or is it too hacky?

+4
source share
1 answer

There are really two options for solving your problem. The first approach is to classify all constants and exceptions and have fewer wider categories. This will allow you to easily navigate to which categories you want. A dictionary (or perhaps nested dictionaries) would be a good way to implement this, since you could support groups with names in them. The second way you could do this if you wanted to tweak the controls a bit would be to make a class that acts like a dictionary. He will have a list of children's objects. This way you can make unique, simpler ways to access navigation through all your constants and exceptions, such as a new exception class that handles several such exceptions. Another way to make it cleaner that would require access to the source would be to exclude all of these exceptions into a smaller group of exceptions that could handle groups of similar problems. This will probably be the best way to handle exceptions, but you may not have access to the source to change this.

+1
source

Source: https://habr.com/ru/post/1480096/


All Articles