pythonpipenvmypypython-config

Python ConfigParser .ini parsing and portable variable substitutions


I want to have a .ini entry that references special variables e.g.

[magic_module]
magic_directory: ${env:PWD}/magic

currently, I have the non-portable

[magic_module]
magic_directory: C:/Users/user1/projects/project1/magic

I would like to have a .ini path entry that is more portable instead of hard-coded to my computer. Does the Python ConfigParser natively perform substitutions like this?


This is slightly different than SO question ConfigParser and String interpolation with env variable because I am wondering about any possible default interpolated variables, not just environment variables.

This is for passing information to a different module (mypy) that uses ConfigParser.

Specifically, this is for improving portability in a Python package. I'm trying to set the mypy_path within a mypy.ini while working with a pipenv-created virtualenv python environment. The user install module paths will change so I want to portably set that for mypy.

Using Python 3.7.


Solution

  • By setting the parameter value interpolation to an instance of the class ExtendedInterpolation you can meet your objective. See example below. This is tested on Python 3.9.7.

    sample.ini

    In the following example, I am:

    [magic_module]
    magic_directory: ${WINDIR}/magic
    
    [another_section]
    another_directory=${magic_module:magic_directory}\folder1\folder2
    

    main.py

    import configparser
    import os
    
    def display_setting(config: configparser.ConfigParser,section: str, key: str):
        value=config.get(section, key)
        print(f"Value of {section}:{key}={value}")
    
    print("Begin....")
    config = configparser.ConfigParser(os.environ, interpolation=configparser.ExtendedInterpolation())
    sample_ini_file=os.path.join(os.path.dirname(__file__),"sample.ini")
    print(f"Going to load the INI file {sample_ini_file}")
    config.read(sample_ini_file)
    
    display_setting(config=config, section="magic_module", key="magic_directory")
    display_setting(config=config, section="another_section", key="another_directory")
    
    
    

    Output

    Begin....
    Going to load the INI file C:\work\sample.ini   
    Value of magic_module:magic_directory=C:\WINDOWS/magic
    Value of another_section:another_directory=C:\WINDOWS/magic\folder1\folder2
    
    

    Link to documentation

    https://docs.python.org/3.9/library/configparser.html#interpolation-of-values