A potential "con" of the Python file approach is that your user can put arbitrary code in the file that will be executed in your application's context. As S. Lott points out in the comments to this answer (when I was somewhat more forceful in my warning), this is usually not an issue because the user (or a hacker) will usually have access to your entire source code anyway and can make any desired changes.
However, I can certainly imagine situations in which the approach could result in a new security hole, such as when the main script files are writable only by the system administrator and the per-user config file is the only file editable by the end user. Unless you are certain that your code will never run in such an environment, I would not recommend the Python module approach. There are good reasons that "don't execute code given to you by users" is widely considered a best practice.
Executing the config file also makes handling errors problematic. If the user introduces a syntax error, you will want to trap it, and you can do so easily by throwing a try
around your import
, but nothing after the error will be executed. In a config file, usually parsing will continue with the next line, so the user will miss at most one setting instead of (say) half of them. There are ways to make a Python module work more like a config file (you could read the file as text and exec()
each line, for example) but if you have to do any work at all, it becomes easier to use ConfigParser
.
If, despite all this, you still want to use Python syntax in your config file, you could use the ast
module (see function literal_eval()
).