tags:

views:

34

answers:

1

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).

+2  A: 

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.

aaronasterling
Personally, I think the worst way to do is with a settings file like django. But +1 for mentioning ConfigParser.
Attila Oláh
Actually, I probably didn't word my question very well. When I said "configuration settings for a module" I meant within Python. So, perhaps a better question: when you import a module, what's the best way to setup module-level state/parameters at runtime, within Python? For example, when you instantiate a class, a common pythonic way to setup class-level state is with parameters to the __init__ function. What's the __init__ function for a module?
bryhoyt
And, more to the point (because it's easy to put runtime code directly in the module, like an __init__ function), how do I pass parameters to the modules "__init__" function?
bryhoyt
@bryhoyt I think that what you are describing is pretty much the second of the three options that I covered.
aaronasterling