Python configuration file: Any file format recommendation? INI format still appropriate? Seems quite old school

前端 未结 8 1739
执念已碎
执念已碎 2020-12-04 10:43

I need to store configurations (key/value) for a Python application and I am searching for the best way to store these configurations in a file.

I run into Python\'s

8条回答
  •  一个人的身影
    2020-12-04 11:00

    Consider using plain Python files as configuration files.

    An example (config.py):

    # use normal python comments
    
    value1 = 32
    value2 = "A string value"
    
    value3 = ["lists", "are", "handy"]
    value4 = {"and": "so", "are": "dictionaries"}
    

    In your program, load the config file using exec (docs):

    from pathlib import Path
    
    if __name__ == "__main__":
        config = {}
        exec(Path("config.py").read_text(encoding="utf8"), {}, config)
        
        print config["value1"]
        print config["value4"]
    

    I like this approach, for the following reasons:

    • In the simple case, the format is as easy to author as an INI-style config file. It also shares an important characteristic with INI files: it is very suitable for version control (this is less true for XML and maybe also for JSON)
    • I like the flexibility that comes with having the config file in an actual programming language.

    The approach is widely used, a few examples:

    • A Django site's settings lives inside settings.py. Django does not use execfile, it uses import to read/execute settings.py AFAIK, but the end result is the same: the code inside the settings file is executed.
    • The bash shell reads and executes ~/.bashrc on startup.
    • The Python interpreter imports site.py on startup.

提交回复
热议问题