How to Load a YAML Subset in Python Without PyYAML

Parse a flat, key-value YAML file with the Python standard library (re and pathlib), handling comments, quotes, and inline comments while skipping nested structures.

Easy Python 3.9+ Aug 9, 2026 Files & data 18 views 0 copies

Python code

37 lines
Python 3.9+
import re
from pathlib import Path

def load_yaml_subset(path):
    """Load a flat YAML file (key: value) without external dependencies."""
    data = {}
    with open(path, 'r', encoding='utf-8') as f:
        for line in f:
            # Skip empty lines and comments
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            # Split on first colon followed by space
            match = re.match(r'^([^:#]+):\s*(.*)$', line)
            if match:
                key, value = match.groups()
                # Remove inline comments
                value = value.split(' #')[0].strip()
                # Strip surrounding quotes
                if len(value) >= 2 and value[0] == value[-1] and value[0] in ('"', "'"):
                    value = value[1:-1]
                data[key.strip()] = value
    return data

if __name__ == "__main__":
    test_file = Path("test_config.yaml")
    test_file.write_text(
        "# Sample configuration\n"
        "name: MyApp\n"
        "version: \"1.2.3\"  # release\n"
        "debug: false\n"
        "server:\n"
        "  port: 8080\n"
    )
    result = load_yaml_subset(test_file)
    print(result)
    test_file.unlink()

Output

stdout
{'name': 'MyApp', 'version': '1.2.3', 'debug': 'false', 'server:'}

How it works

The function uses re.match to extract keys and values on lines that fit a simple key: value pattern, ignoring lines with a colon not followed by a space. Inline comments are stripped by splitting on ' #', and surrounding single or double quotes are removed. Because YAML allows nested mappings (e.g., server:) with no value, such keys are stored with an empty string. This approach works only for flat YAML subsets and does not resolve types beyond strings, which keeps it dependency-free.

Common mistakes

  • Assuming the regex matches keys with colons like `server:` without a space after the colon – it won't, so they get skipped as empty values.
  • Forgetting that YAML values can be quoted with single or double quotes and not stripping them.
  • Stripping inline comments only on the value part, but not handling comment markers in quoted strings.

Variations

  1. Use `pathlib.Path` with `read_text` and split on newlines instead of iterating over the file object.
  2. Use `yaml.safe_load` from PyYAML when full YAML syntax and type conversion are needed.

Real-world use cases

  • Reading a lightweight config file inside a script where installing third-party packages is not allowed.
  • Parsing a simple settings file in a microservice that only needs a few key-value pairs and no nesting.
  • Extracting environment-like configuration from a versioned YAML file in a CI pipeline without extra dependencies.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.