Python: What is the recommended way to set configuration parameters for a module when importing it?

I saw how people used monkey patch to set parameters in a module, for example:

import mymodule
mymodule.default_img = "/my/file.png"
mymodule.view_default_img ()

And Django, for example, has settings.py for the whole Django application, and it always solves me a bit.

What are other ways to manage configuration settings in a module? What is recommended? It often seems that there is no good way to configure the configuration at the module level.

Obviously, a complete configuration exception is most preferable, and it is usually best to use classes or pass an argument to a function. But sometimes you can’t avoid any settings, and sometimes it really makes sense to have global parameters for the whole module just for convenience (for example, the Django template system - specifying the base path for each template will be a nightmare, definitely not a good DRY code).

+6
python
source share
1 answer

One option is the ConfigParser module. You can have settings in a configuration file other than python, and each module will read its settings from this. Another option is to have a config method in each module, which can also pass client code.

# foo.py setting1 = 0 setting2 = 'foo' def configure(config1, config2): global setting1, setting2 setting1 = config1 setting2 = config2 

Then in the import module

 import foo foo.configure(42, 'bar') 

Personally, I think the best way to do this is with a settings file like django.

+3
source share

All Articles