1

I wanted to mix a config.py approach and ConfigParser to set some default values in config.py which could be overridden by the user in its root folder:

import ConfigParser
import os

CACHE_FOLDER = 'cache'
CSV_FOLDER = 'csv'

def main():
    cp = ConfigParser.ConfigParser()
    cp.readfp(open('defaults.cfg'))
    cp.read(os.path.expanduser('~/.python-tools.cfg'))
    CACHE_FOLDER = cp.get('folders', 'cache_folder')
    CSV_FOLDER = cp.get('folders', 'csv_folder')

if __name__ == '__main__':
    main()

When running this module I can see the value of CACHE_FOLDER being changed. However when in another module I do the following:

import config

def main()
    print config.CACHE_FOLDER

This will print the original value of the variable ('cache').

Am I doing something wrong ?

1 Answer 1

1

The main function in the code you show only gets run when that module is run as a script (due to the if __name__ == '__main__' block). If you want that turn run any time the module is loaded, you should get rid of that restriction. If there's extra code that actually does something useful in the main function, in addition to setting up the configuration, you might want to split that part out from the setup code:

def setup():
    # the configuration stuff from main in the question

def main():
    # other stuff to be done when run as a script

setup()  # called unconditionally, so it will run if you import this module

if __name__ == "__main__":
    main()  # this is called only when the module is run as a script
Sign up to request clarification or add additional context in comments.

1 Comment

Ah I misunderstood I thought that main() would be called unconditionally and the part after the if would be only run in script. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.