Hone logo
Hone
Problems

Python INI File Parser

INI files are a common configuration file format used by many applications. They offer a simple, human-readable way to store settings. Implementing a parser for this format in Python will allow you to dynamically load and manage application configurations, making your programs more flexible and easier to update.

Problem Description

Your task is to create a Python class or set of functions that can parse an INI file and represent its contents in a structured way. The parser should handle sections, key-value pairs within sections, and ignore comments.

Key Requirements:

  1. Section Handling: The parser must recognize sections defined by [section_name].
  2. Key-Value Pairs: Within each section, it should parse lines in the format key = value. Both keys and values are strings.
  3. Comment Handling: Lines starting with # or ; should be treated as comments and ignored. Empty lines should also be ignored.
  4. Data Structure: The parsed data should be stored in a nested dictionary-like structure. The top-level keys will be section names, and the values will be dictionaries of key-value pairs for that section.
  5. No Sections: If a key-value pair appears before any [section] header, it should be placed in a default section, often referred to as [DEFAULT] or []. You can choose how to represent this default section (e.g., a special key in the main dictionary).
  6. Value Types: For this challenge, all values should be treated as strings. No automatic type conversion (like to integers or booleans) is required.
  7. Whitespace: Leading/trailing whitespace around section names, keys, and values should be stripped. Whitespace within values should be preserved.

Expected Behavior:

  • The parser should read an INI file (provided as a string or file path).
  • It should return a Python dictionary representing the INI structure.
  • Errors related to malformed lines (e.g., a key without a value or an equals sign) can be ignored or raise an exception, depending on your design choice. For simplicity, we'll focus on successful parsing for this challenge.

Edge Cases:

  • Empty INI file.
  • File with only comments and empty lines.
  • Sections with no key-value pairs.
  • Key-value pairs before the first section.
  • Keys or values containing spaces or special characters (excluding the delimiter =).
  • Duplicate keys within the same section (the last one encountered should overwrite previous ones).

Examples

Example 1:

Input:

[DEFAULT]
version = 1.0
debug = false

[Database]
host = localhost
port = 5432
user = admin

; This is a comment
[Logging]
level = INFO
file = app.log

Output:

{
    "DEFAULT": {
        "version": "1.0",
        "debug": "false"
    },
    "Database": {
        "host": "localhost",
        "port": "5432",
        "user": "admin"
    },
    "Logging": {
        "level": "INFO",
        "file": "app.log"
    }
}

Explanation: The parser correctly identifies the [DEFAULT], [Database], and [Logging] sections. Key-value pairs are parsed and assigned to their respective sections. Comments and empty lines are ignored.

Example 2:

Input:

# Application settings
name = My App
author = AI Mentor

[Server]
port = 8080
timeout = 30

Output:

{
    "DEFAULT": {
        "name": "My App",
        "author": "AI Mentor"
    },
    "Server": {
        "port": "8080",
        "timeout": "30"
    }
}

Explanation: Key-value pairs found before the first [Server] section are placed in a "DEFAULT" section.

Example 3:

Input:

[Section1]
key1 = value1
key2 = value with spaces
key1 = another value # Duplicate key

[Section2]

Output:

{
    "Section1": {
        "key1": "another value",
        "key2": "value with spaces"
    },
    "Section2": {}
}

Explanation: The duplicate key1 in [Section1] is overwritten by the last occurrence. An empty section [Section2] results in an empty dictionary for that section.

Constraints

  • The input INI string will not exceed 1000 lines.
  • Section names, keys, and values will not contain newlines.
  • The equals sign (=) will be used as the delimiter between keys and values.
  • Your parser should be reasonably efficient and should not take excessively long for typical INI file sizes.

Notes

Consider how you will handle the case where a key-value pair might appear without an = sign, or an empty line that looks like a key. For this challenge, you can assume valid key-value pairs will always have an equals sign.

A good approach might involve iterating through the lines of the input string, maintaining a current section, and processing each line based on its content (section header, comment, key-value pair, or empty line).

Loading editor...
python