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

option-access.mddocs/

Option Access

Methods for accessing, setting, and managing configuration options with comprehensive type conversion support. These methods provide the primary interface for reading and writing configuration values.

Capabilities

Getting Option Values

Retrieve configuration values with support for type conversion, fallback values, and variable interpolation.

def get(section, option, *, raw=False, vars=None, fallback=_UNSET):
    """
    Get an option value as a string.
    
    Parameters:
    - section: str, section name
    - option: str, option name
    - raw: bool, disable interpolation if True
    - vars: dict, additional interpolation variables
    - fallback: any, value to return if option doesn't exist
    
    Returns:
    str: option value after interpolation
    
    Raises:
    - NoSectionError: if section doesn't exist
    - NoOptionError: if option doesn't exist and no fallback
    """

def getint(section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs):
    """
    Get an option value as an integer.
    
    Parameters:
    - section: str, section name
    - option: str, option name
    - raw: bool, disable interpolation if True
    - vars: dict, additional interpolation variables
    - fallback: any, value to return if option doesn't exist
    
    Returns:
    int: option value converted to integer
    
    Raises:
    - NoSectionError: if section doesn't exist
    - NoOptionError: if option doesn't exist and no fallback
    - ValueError: if value cannot be converted to int
    """

def getfloat(section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs):
    """
    Get an option value as a float.
    
    Parameters:
    - section: str, section name
    - option: str, option name
    - raw: bool, disable interpolation if True
    - vars: dict, additional interpolation variables
    - fallback: any, value to return if option doesn't exist
    
    Returns:
    float: option value converted to float
    
    Raises:
    - NoSectionError: if section doesn't exist
    - NoOptionError: if option doesn't exist and no fallback
    - ValueError: if value cannot be converted to float
    """

def getboolean(section, option, *, raw=False, vars=None, fallback=_UNSET, **kwargs):
    """
    Get an option value as a boolean.
    
    Parameters:
    - section: str, section name
    - option: str, option name
    - raw: bool, disable interpolation if True
    - vars: dict, additional interpolation variables
    - fallback: any, value to return if option doesn't exist
    
    Returns:
    bool: option value converted to boolean
    
    Raises:
    - NoSectionError: if section doesn't exist
    - NoOptionError: if option doesn't exist and no fallback
    - ValueError: if value cannot be converted to bool
    
    Notes:
    - True values: '1', 'yes', 'true', 'on' (case-insensitive)
    - False values: '0', 'no', 'false', 'off' (case-insensitive)
    """

Setting Option Values

Methods to set and modify configuration option values.

def set(section, option, value=None):
    """
    Set an option value.
    
    Parameters:
    - section: str, section name
    - option: str, option name
    - value: str or None, option value
    
    Returns:
    None
    
    Raises:
    - NoSectionError: if section doesn't exist
    - TypeError: if value is not string or None (when allow_no_value=True)
    
    Notes:
    - Value is converted to string if not None
    - None values allowed only when allow_no_value=True
    """

Option Validation and Listing

Methods to check option existence and retrieve option information.

def has_option(section, option):
    """
    Check if an option exists in a section.
    
    Parameters:
    - section: str, section name
    - option: str, option name
    
    Returns:
    bool: True if option exists, False otherwise
    
    Notes:
    - Returns False if section doesn't exist
    - Case-sensitive comparison
    """

def options(section):
    """
    Return list of option names for a section.
    
    Parameters:
    - section: str, section name
    
    Returns:
    list of str: option names in the section
    
    Raises:
    - NoSectionError: if section doesn't exist
    
    Notes:
    - Includes options from DEFAULT section
    - Returns options in order of appearance
    """

def items(section=_UNSET, raw=False, vars=None):
    """
    Return list of (name, value) tuples for options or sections.
    
    Parameters:
    - section: str, section name (if provided, returns option-value pairs for that section)
    - raw: bool, disable interpolation if True
    - vars: dict, additional interpolation variables
    
    Returns:
    - If section specified: list of tuple (option_name, option_value) pairs for that section
    - If section not specified: list of tuple (section_name, SectionProxy) pairs for all sections
    
    Raises:
    - NoSectionError: if specified section doesn't exist
    
    Notes:
    - When getting section items, includes options from DEFAULT section
    - When getting all sections, includes DEFAULT section if it has options
    """

def remove_option(section, option):
    """
    Remove an option from a section.
    
    Parameters:
    - section: str, section name
    - option: str, option name to remove
    
    Returns:
    bool: True if option existed and was removed, False otherwise
    
    Raises:
    - NoSectionError: if section doesn't exist
    """

Usage Examples

Basic Value Retrieval

from backports import configparser

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

# Get string values
host = config.get('database', 'host')
name = config.get('database', 'name', fallback='default_db')

# Get typed values
port = config.getint('database', 'port')
timeout = config.getfloat('database', 'timeout')
debug = config.getboolean('application', 'debug')

Working with Fallback Values

from backports import configparser

config = configparser.ConfigParser()

# Provide fallback for missing options
cache_size = config.getint('cache', 'size', fallback=1000)
enable_logging = config.getboolean('logging', 'enabled', fallback=True)

# Use None fallback to detect missing options
api_key = config.get('api', 'key', fallback=None)
if api_key is None:
    print("API key not configured")

Setting Option Values

from backports import configparser

config = configparser.ConfigParser()
config.add_section('database')

# Set string values
config.set('database', 'host', 'localhost')
config.set('database', 'port', '5432')

# Set typed values (converted to strings)
config.set('database', 'timeout', str(30.5))
config.set('database', 'debug', str(True))

# Set None values (if allow_no_value=True)
config = configparser.ConfigParser(allow_no_value=True)
config.add_section('optional')
config.set('optional', 'empty_option', None)

Boolean Value Handling

from backports import configparser

config = configparser.ConfigParser()
config.read_string('''
[settings]
debug = yes
production = no
feature_flag = true
maintenance = false
enabled = 1
disabled = 0
''')

# All these return appropriate boolean values
debug = config.getboolean('settings', 'debug')        # True
prod = config.getboolean('settings', 'production')    # False
flag = config.getboolean('settings', 'feature_flag')  # True
maint = config.getboolean('settings', 'maintenance')  # False
enabled = config.getboolean('settings', 'enabled')    # True
disabled = config.getboolean('settings', 'disabled')  # False

Option Validation and Listing

from backports import configparser

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

# Check option existence
if config.has_option('database', 'password'):
    password = config.get('database', 'password')

# List all options in a section
db_options = config.options('database')
print(f"Database options: {db_options}")

# Get all option-value pairs
db_items = config.items('database')
for name, value in db_items:
    print(f"{name} = {value}")

Variable Interpolation

from backports import configparser

config = configparser.ConfigParser()
config.read_string('''
[DEFAULT]
base_url = http://localhost
port = 8080

[api]
endpoint = %(base_url)s:%(port)s/api
''')

# Get interpolated value
endpoint = config.get('api', 'endpoint')  # 'http://localhost:8080/api'

# Disable interpolation
raw_endpoint = config.get('api', 'endpoint', raw=True)  # '%(base_url)s:%(port)s/api'

# Provide additional variables
extra_vars = {'version': 'v2'}
versioned_endpoint = config.get('api', 'endpoint', vars=extra_vars)

Error Handling

from backports import configparser

config = configparser.ConfigParser()

try:
    value = config.get('nonexistent', 'option')
except configparser.NoSectionError:
    print("Section doesn't exist")

try:
    value = config.get('existing_section', 'nonexistent_option')
except configparser.NoOptionError:
    print("Option doesn't exist")

try:
    number = config.getint('section', 'not_a_number')
except ValueError:
    print("Value cannot be converted to integer")

SectionProxy Option Access

from backports import configparser

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

# Access options through section proxy
db_section = config['database']
host = db_section['host']
port = db_section.getint('port')
debug = db_section.getboolean('debug', fallback=False)

# Set options through section proxy
db_section['new_option'] = 'new_value'
del db_section['old_option']

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