Config file with a .py file

前端 未结 4 440
南笙
南笙 2021-01-22 08:39

I have been told that doing this would be a not-very-good practice:

configfile.py

SOUNDENABLED = 1
FILEPATH = \'D:\\\\TEMP\\\\hello.txt\'


        
相关标签:
4条回答
  • 2021-01-22 09:02

    Importing a module executes any code that it contains. Nothing restricts your configfile.py to containing only definitions. Down the line, this is a recipe for security concerns and obscure errors. Also, you are bound to Python's module search path for finding the configuration file. What if you want to place the configuration file somewhere else, or if there is a name conflict?

    0 讨论(0)
  • 2021-01-22 09:04

    The only concern here is that a .py can have arbitrary Python code, so it has a potential to break your program in arbitrary ways.

    If you can trust your users to use it responsibly, there's nothing wrong with this setup. If fact, at one of my previous occupations, we were doing just that, without any problems that I'm aware of. Just on the contrary: it allowed users to eliminate duplication by autogenerating repetitive parts and importing other config files.

    Another concern is if you have many files, the configuration ones are better be separated from regular code ones, so users know which files they are supposed to be able to edit (the above link addresses this, too).

    0 讨论(0)
  • 2021-01-22 09:12

    This is a perfectly acceptable practice. Some examples of well-known projects using this method are Django and gunicorn.

    0 讨论(0)
  • 2021-01-22 09:19

    It could be better for some reasons

    1. The only extension that config file could have is py.
    2. You cannot distribute your program with configs in separate directory unless you put an __init__.py into this directory
    3. Nasty users of your program can put any python script in config and do bad things.

    For example, the YouCompleteMe autocompletion engine stores config in python module, .ycm_extra_conf.py. By default, each time config is imported, it asks you, whether you sure that the file is safe to be executed.

    1. How would you change configuration without restarting your app?

    Generally, allowing execution of code that came from somewhere outside is a vulnerability, that could lead to very serious consequences.

    However, if you don't care about these, for example, you are developing web application that executes only on your server, this is an acceptable practice to put configuration into python module. Django does so.

    0 讨论(0)
提交回复
热议问题