CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-configparser

Updated configparser from stdlib for earlier Pythons with enhanced configuration file parsing capabilities.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

parser-classes.mddocs/

Parser Classes

Core configuration parser classes that provide the main functionality for reading, writing, and manipulating configuration files. These classes form the foundation of the configparser library.

Capabilities

ConfigParser

Main configuration parser class with interpolation support, extending RawConfigParser with value substitution capabilities.

class ConfigParser(RawConfigParser):
    """
    Configuration file parser with interpolation support.
    
    Parameters:
    - defaults: dict, default values for all sections
    - dict_type: type, dictionary class for sections and options
    - allow_no_value: bool, allow options without values
    - delimiters: tuple, characters that separate keys from values ('=', ':')
    - comment_prefixes: tuple, characters that start comments ('#', ';')
    - inline_comment_prefixes: tuple, characters for inline comments
    - strict: bool, disallow duplicate sections/options
    - empty_lines_in_values: bool, preserve empty lines in multiline values
    - default_section: str, name of the default section ('DEFAULT')
    - interpolation: Interpolation, interpolation handler
    - converters: dict, custom type converters
    - allow_unnamed_section: bool, allow options without section headers
    """
    
    def __init__(self, defaults=None, dict_type=dict, allow_no_value=False,
                 delimiters=('=', ':'), comment_prefixes=('#', ';'),
                 inline_comment_prefixes=None, strict=True,
                 empty_lines_in_values=True, default_section='DEFAULT',
                 interpolation=BasicInterpolation(), converters=None,
                 allow_unnamed_section=False): ...

RawConfigParser

Base configuration parser without interpolation support, suitable for configuration files that contain literal % symbols.

class RawConfigParser(MutableMapping):
    """
    Configuration file parser without interpolation.
    
    Parameters: Same as ConfigParser
    """
    
    def __init__(self, defaults=None, dict_type=dict, allow_no_value=False,
                 delimiters=('=', ':'), comment_prefixes=('#', ';'),
                 inline_comment_prefixes=None, strict=True,
                 empty_lines_in_values=True, default_section='DEFAULT',
                 interpolation=None, converters=None,
                 allow_unnamed_section=False): ...
    
    def defaults(self):
        """
        Return the dictionary of default values.
        
        Returns:
        dict: copy of the defaults dictionary
        """
    
    def popitem(self):
        """
        Remove and return an arbitrary (section_name, section_proxy) pair.
        
        Returns:
        tuple: (section_name, section_proxy) pair
        
        Raises:
        KeyError: if parser is empty
        """
    
    def optionxform(self, optionstr):
        """
        Transform option names on every read, get, or set operation.
        
        Default implementation converts to lowercase.
        
        Parameters:
        - optionstr: str, original option name
        
        Returns:
        str: transformed option name
        """
    
    @property
    def converters(self):
        """
        Access to the ConverterMapping for custom type converters.
        
        Returns:
        ConverterMapping: mapping of converter names to functions
        """

SectionProxy

Dictionary-like proxy object for accessing individual configuration sections, providing convenient access to options within a section.

class SectionProxy(MutableMapping):
    """
    Proxy object for accessing options within a configuration section.
    
    Supports dictionary-like operations for getting, setting, and 
    checking option existence within the section.
    """
    
    def __getitem__(self, key): ...
    def __setitem__(self, key, value): ...
    def __delitem__(self, key): ...
    def __contains__(self, key): ...
    def __iter__(self): ...
    def keys(): ...
    def values(): ...
    def items(): ...
    
    def get(self, option, fallback=None, *, raw=False, vars=None, **kwargs):
        """
        Get option value with fallback support.
        
        Parameters:
        - option: str, option name
        - fallback: any, value to return if option doesn't exist
        - raw: bool, disable interpolation if True
        - vars: dict, additional interpolation variables
        - **kwargs: additional arguments for custom converters
        
        Returns:
        str: option value or fallback
        """
    
    @property
    def parser(self):
        """
        Reference to the parent ConfigParser instance.
        
        Returns:
        ConfigParser: the parser that owns this section (read-only)
        """
    
    @property
    def name(self):
        """
        Name of the section this proxy represents.
        
        Returns:
        str: section name (read-only)
        """

ConverterMapping

Mapping interface for custom type converters, allowing registration of custom conversion functions for specific data types.

class ConverterMapping(MutableMapping):
    """
    Mapping for custom type converters.
    
    Allows registration of custom conversion functions that transform
    string configuration values into specific Python types. When a 
    converter is registered, corresponding get* methods are automatically
    created on the parser and section proxies.
    """
    
    def __init__(self, parser):
        """
        Initialize converter mapping for a parser.
        
        Parameters:
        - parser: ConfigParser, the parent parser instance
        """
    
    def __getitem__(self, key):
        """
        Get a converter function by name.
        
        Parameters:
        - key: str, converter name
        
        Returns:
        callable: converter function
        
        Raises:
        KeyError: if converter doesn't exist
        """
    
    def __setitem__(self, key, value):
        """
        Register a converter function.
        
        Parameters:
        - key: str, converter name (becomes method suffix)
        - value: callable, converter function that takes string and returns converted value
        
        Notes:
        - Creates get{key}() method on parser and section proxies
        - Converter name should be valid Python identifier
        """
    
    def __delitem__(self, key):
        """
        Remove a converter and its associated methods.
        
        Parameters:
        - key: str, converter name to remove
        
        Raises:
        KeyError: if converter doesn't exist
        """
    
    def __contains__(self, key): ...
    def __iter__(self): ...
    def __len__(self): ...
    def keys(self): ...
    def values(self): ...
    def items(self): ...

Usage Examples

Basic ConfigParser Usage

from backports import configparser

# Create parser with basic interpolation
config = configparser.ConfigParser()

# Create parser with custom settings
config = configparser.ConfigParser(
    defaults={'host': 'localhost', 'port': '8080'},
    allow_no_value=True,
    delimiters=('=', ':'),
    comment_prefixes=('#', ';'),
    strict=True
)

RawConfigParser Usage

from backports import configparser

# Use RawConfigParser when interpolation is not desired
config = configparser.RawConfigParser()

# Useful for configuration files with literal % symbols
config.read('config_with_percent_signs.ini')

SectionProxy Usage

from backports import configparser

config = configparser.ConfigParser()
config.read('config.ini')

# Access section as dictionary-like object
section = config['database']
host = section['host']
port = section.getint('port')

# Modify section options
section['timeout'] = '30'
del section['deprecated_option']

# Check option existence
if 'cache_size' in section:
    cache_size = section.getint('cache_size')

Custom Converters

from backports import configparser

def list_converter(value):
    return [item.strip() for item in value.split(',')]

def json_converter(value):
    import json
    return json.loads(value)

# Register converters during initialization
config = configparser.ConfigParser(
    converters={'list': list_converter, 'json': json_converter}
)

config.read_string('''
[section]
items = apple, banana, cherry
settings = {"debug": true, "timeout": 30}
''')

# Use custom converters
items = config.getlist('section', 'items')  # ['apple', 'banana', 'cherry']
settings = config.getjson('section', 'settings')  # {'debug': True, 'timeout': 30}

# Access converters mapping
print(config.converters.keys())  # dict_keys(['list', 'json'])

# Add converter dynamically
config.converters['path'] = lambda x: x.replace('/', '\\')
normalized_path = config.getpath('section', 'some_path')

# Remove converter
del config.converters['json']
# Now config.getjson() method is no longer available

ConverterMapping Usage

from backports import configparser

config = configparser.ConfigParser()

# Access the converters mapping
converters = config.converters

# Add converters dynamically
def duration_converter(value):
    """Convert 'XhYm' format to minutes"""
    import re
    match = re.match(r'(\d+)h(\d+)m', value)
    if match:
        hours, minutes = map(int, match.groups())
        return hours * 60 + minutes
    return int(value)

converters['duration'] = duration_converter

config.read_string('''
[timeouts]
short = 5m
long = 2h30m
''')

# Use the dynamically added converter
short_timeout = config.getduration('timeouts', 'short')  # 5
long_timeout = config.getduration('timeouts', 'long')    # 150

# Check converter existence
if 'duration' in converters:
    print("Duration converter is available")

# Iterate through converters
for name, func in converters.items():
    print(f"Converter: {name}")

Install with Tessl CLI

npx tessl i tessl/pypi-configparser

docs

exception-handling.md

file-operations.md

index.md

interpolation.md

option-access.md

parser-classes.md

section-management.md

tile.json