Skip to content

ConfigRead Manual

Ulrond edited this page Oct 15, 2024 · 1 revision

Overview

The ConfigRead class simplifies loading and accessing configuration data from YAML files. It provides a user-friendly way to interact with YAML data using dot notation, indexing, or dictionary-style access.

Class Definition

class ConfigRead:
    """
    A class to represent configuration data loaded from a YAML file.
    ...
    """

    def __init__(self, data=None, start_key=None ):
        """
        Initializes the ConfigRead object by loading data from a YAML file.
        ...
        """
        # ... (Initialization logic) ...

    def __str__(self):
        # ... (String representation) ...

    def __load_yaml__(self,input_var):
        """
        Loads YAML data from a file or a dictionary.
        ...
        """
        # ... (Implementation) ...

    def _set_attributes(self, data):
        """
        Recursively sets object attributes from YAML data.
        ...
        """
        # ... (Implementation) ...

    def append(self, value):
        """
        Appends an item to the internal list.
        ...
        """
        # ... (Implementation) ...

    def get(self, field_path:dict|list):
        """
        Retrieves the value associated with a specified field path within the YAML data.
        ...
        """
        # ... (Implementation) ...

Initialization

  • data: A string representing the YAML file path or a file-like object containing YAML data.
  • start_key (optional): If provided, the processing starts from this key within the YAML data.

Methods

  • __load_yaml__(input_var): Loads YAML data from a file or a dictionary.
  • _set_attributes(data): Recursively sets object attributes from YAML data.
  • append(value): Appends an item to the internal list (used for handling lists in YAML).
  • get(field_path): Retrieves the value at the specified field path using dot notation (e.g., "section.key").

Features

  • Flexible Access: Access YAML values using dot notation (e.g., config.section.key), indexing (e.g., config['section']['key']), or dictionary-style access (e.g., config.fields['section']['key']).
  • Handles Numeric Keys: Automatically prefixes numeric keys in YAML with an underscore '_' to make them valid Python attribute names.
  • Nested Structure Support: Seamlessly handles nested dictionaries and lists within the YAML data.

Example Usage

# Load YAML data from a file
config = ConfigRead("config.yaml")

# Access values using dot notation
host = config.database.host
port = config.database.port

# Access values using indexing
name = config['application']['name']
languages = config['application']['languages']

# Access values using the 'fields' attribute
version = config.fields['application']['version']

This manual provides a basic understanding of the ConfigRead class and its functionalities. Refer to the code documentation and examples for more detailed information and advanced use cases.