Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually building a deep copy of a ConfigParser in Python 2.7

Just starting in on my Python learning curve, and hitting a snag in porting some code up to Python 2.7. It appears that in Python 2.7 it is no longer possible to perform a deepcopy() on instances of ConfigParser. It also appears that the Python team isn't terribly interested in restoring such a capability:

http://bugs.python.org/issue16058

Can someone propose an elegant solution for manually constructing a deepcopy/duplicate of an instance of ConfigParser?

Many thanks, -Pete

like image 722
Pete E. Avatar asked May 01 '14 20:05

Pete E.


People also ask

How do I print a Configparser object?

Just use a StringIO object and the configparser's write method. It looks like the only method for "printing" the contents of a config object is ConfigParser. write which takes a file-like object.

How do I use Configparser in Python?

Read and parse one configuration file, given as a file object. Read configuration from a given string. Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section.

Is Configparser included in Python?

Python's ConfigParser module is part of the standard library. The module provides a parser for simple configuration files consisting of groups of named values.


2 Answers

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
like image 125
gerardw Avatar answered Sep 20 '22 02:09

gerardw


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)
like image 36
Charles Avatar answered Sep 21 '22 02:09

Charles