Manually building a deep copy of a ConfigParser in Python 2.7

The previous solution doesn't work in all python3 use cases. Specifically if the original parser is using Extended Interpolation the copy may fail to work correctly. Fortunately, the easy solution is to use the pickle module:

def deep_copy(config:configparser.ConfigParser)->configparser.ConfigParser:
    """deep copy config"""
    rep = pickle.dumps(config)
    new_config = pickle.loads(rep)
    return new_config

Based on @Toenex answer, modified for Python 2.7:

import StringIO
import ConfigParser

# Create a deep copy of the configuration object
config_string = StringIO.StringIO()
base_config.write(config_string)

# We must reset the buffer to make it ready for reading.        
config_string.seek(0)        
new_config = ConfigParser.ConfigParser()
new_config.readfp(config_string)

This is just an example implementation of Jan Vlcinsky answer written in Python 3 (I don't have enough reputation to post this as a comment to Jans answer). Many thanks to Jan for the push in the right direction.

To make a full (deep) copy of base_config into new_config just do the following;

import io
import configparser

config_string = io.StringIO()
base_config.write(config_string)
# We must reset the buffer ready for reading.
config_string.seek(0) 
new_config = configparser.ConfigParser()
new_config.read_file(config_string)

If you need new independent copy of ConfigParser, then one option is:

  • have original version of ConfigParser
  • serialize the config file into temporary file or StringIO buffer
  • use that tmpfile or StringIO buffer to create new ConfigParser.

And you have it done.