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

section-management.mddocs/

Section Management

Operations for managing configuration sections including creation, removal, and validation. Sections organize configuration options into logical groups and provide the hierarchical structure of configuration files.

Capabilities

Section Listing and Validation

Methods to retrieve and validate section information within the configuration.

def sections():
    """
    Return list of section names, excluding DEFAULT.
    
    Returns:
    list of str: section names in order of appearance
    
    Notes:
    - DEFAULT section is never included
    - Returns sections in the order they were added/read
    """

def has_section(section):
    """
    Check if a section exists in the configuration.
    
    Parameters:
    - section: str, section name to check
    
    Returns:
    bool: True if section exists, False otherwise
    
    Notes:
    - DEFAULT section always returns False
    - Case-sensitive comparison
    """

Section Creation and Removal

Methods to dynamically add and remove sections from the configuration.

def add_section(section):
    """
    Create a new section in the configuration.
    
    Parameters:
    - section: str, name of the section to create
    
    Returns:
    None
    
    Raises:
    - DuplicateSectionError: if section already exists (when strict=True)
    - ValueError: if section name is 'DEFAULT' or contains '[' or ']'
    
    Notes:
    - Section names are case-sensitive
    - Cannot create DEFAULT section
    """

def remove_section(section):
    """
    Remove a section and all its options.
    
    Parameters:
    - section: str, name of the section to remove
    
    Returns:
    bool: True if section existed and was removed, False otherwise
    
    Notes:
    - Cannot remove DEFAULT section
    - Silently ignores non-existent sections
    """

Usage Examples

Basic Section Management

from backports import configparser

config = configparser.ConfigParser()

# Add sections
config.add_section('database')
config.add_section('cache')
config.add_section('logging')

# List all sections
print(config.sections())  # ['database', 'cache', 'logging']

# Check if sections exist
if config.has_section('database'):
    print("Database section exists")

if not config.has_section('email'):
    config.add_section('email')

Section Removal

from backports import configparser

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

# Remove obsolete section
if config.has_section('deprecated_feature'):
    success = config.remove_section('deprecated_feature')
    print(f"Section removed: {success}")

# Clean up empty sections
for section in config.sections():
    if not config.options(section):  # No options in section
        config.remove_section(section)

Error Handling

from backports import configparser

config = configparser.ConfigParser(strict=True)

try:
    config.add_section('database')
    config.add_section('database')  # Duplicate section
except configparser.DuplicateSectionError as e:
    print(f"Duplicate section error: {e}")

try:
    config.add_section('DEFAULT')  # Invalid section name
except ValueError as e:
    print(f"Invalid section name: {e}")

try:
    config.add_section('section[with]brackets')  # Invalid characters
except ValueError as e:
    print(f"Invalid section name: {e}")

Working with Section Names

from backports import configparser

config = configparser.ConfigParser()

# Section names are case-sensitive
config.add_section('Database')
config.add_section('database')

print(config.sections())  # ['Database', 'database']

# Check existence is case-sensitive
print(config.has_section('Database'))  # True
print(config.has_section('database'))  # True  
print(config.has_section('DATABASE'))  # False

Dynamic Section Management

from backports import configparser

config = configparser.ConfigParser()

# Create sections based on data
services = ['web', 'api', 'worker', 'scheduler']
for service in services:
    section_name = f'service_{service}'
    if not config.has_section(section_name):
        config.add_section(section_name)

# Remove sections matching pattern
sections_to_remove = [s for s in config.sections() if s.startswith('temp_')]
for section in sections_to_remove:
    config.remove_section(section)

Section Management with Dictionary Interface

from backports import configparser

config = configparser.ConfigParser()

# Dictionary-style section creation
config['database'] = {}
config['cache'] = {}

# Check sections using 'in' operator
if 'database' in config:
    print("Database section exists")

# Remove section using del
del config['cache']

# Iterate over sections
for section_name in config:
    print(f"Section: {section_name}")
    section = config[section_name]
    # Work with section...

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