Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: What is the recommended way to set configuration settings for a module when you import it?

Tags:

python

I've seen people use monkey-patching to set options on 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 entire Django app, and it always grates on me a little.

What are the other ways to manage configuration settings on a module? What's recommended? It seems like there's often no nice way to setup module-level configuration.

Obviously, completely avoiding configuration is by far the most preferable, and it's usually better to use classes, or pass in the argument to a function. But sometimes you can't avoid having settings of some sort, and sometimes it really does make sense to have global module-wide settings just for convenience (for example, Django's template system -- having to specify the base path for every template would be a nightmare, definitely not good DRY code).

like image 692
bryhoyt Avatar asked Oct 12 '10 03:10

bryhoyt


People also ask

Which is the correct way to import modules?

To use the module, you have to import it using the import keyword. The function or variables present inside the file can be used in another file by importing the module.

What are the two ways to import module in Python?

So there's four different ways to import: Import the whole module using its original name: pycon import random. Import specific things from the module: pycon from random import choice, randint. Import the whole module and rename it, usually using a shorter variable name: pycon import pandas as pd.

How do you maintain config files in Python?

A good configuration file should meet at least these 3 criteria: Easy to read and edit: It should be text-based and structured in such a way that is easy to understand. Even non-developers should be able to read. Allow comments: Configuration file is not something that will be only read by developers.

Which command is used to import a module in Python?

Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.


1 Answers

One option is the ConfigParser module. You could have the settings in a non-python config file and have each module read its settings out of that. Another option is to have a config method in each module that the client code can pass it's arguments too.

# foo.py
setting1 = 0
setting2 = 'foo'

def configure(config1, config2):
    global setting1, setting2

    setting1 = config1
    setting2 = config2

Then in the importing module,

import foo

foo.configure(42, 'bar')

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

like image 52
aaronasterling Avatar answered Sep 28 '22 07:09

aaronasterling