Parse From Environment

fejao_config_parser.src.parse_from.environment

parse_from.environment.py file for the fejao_config_parser package.

This module defines the ParseFromEnvironment class which is responsible for parsing configuration values from environment variables based on a provided configuration specification.

ParseFromEnvironment

Parse configuration values from environment variables.

This class reads configuration items and retrieves their values from environment variables based on the specified environment variable names. It converts string environment variable values to their appropriate Python types as defined in the configuration.

The class follows a multi-step process: 1. Stores the configuration list 2. Iterates through each configuration item 3. Retrieves environment variable values by their env_name 4. Converts string values to the specified type (string, bool, int, float, list, dict) 5. Validates the parsed values against the configuration

Attributes:
  • config (list) –

    List of configuration dictionaries containing: name, type, default, and env_name keys.

  • value_from_type (ValuesFromType) –

    Instance for converting string values to appropriate types.

  • values (dict) –

    Dictionary of parsed environment variables mapped by configuration name.

Raises:
  • ValueError –

    If type conversion fails or configuration validation fails.

Example

import os os.environ["DATABASE_URL"] = "postgresql://localhost" os.environ["MAX_CONNECTIONS"] = "10" config = [ ... { ... "name": "db_url", ... "type": "string", ... "default": "sqlite:///:memory:", ... "env_name": "DATABASE_URL" ... }, ... { ... "name": "max_conn", ... "type": "int", ... "default": 5, ... "env_name": "MAX_CONNECTIONS" ... } ... ] parser = ParseFromEnvironment(config=config) parser.get_values() {'db_url': 'postgresql://localhost', 'max_conn': 10}

Source code in fejao_config_parser/src/parse_from/environment.py
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
class ParseFromEnvironment:
    """Parse configuration values from environment variables.

    This class reads configuration items and retrieves their values from environment
    variables based on the specified environment variable names. It converts string
    environment variable values to their appropriate Python types as defined in the
    configuration.

    The class follows a multi-step process:
    1. Stores the configuration list
    2. Iterates through each configuration item
    3. Retrieves environment variable values by their `env_name`
    4. Converts string values to the specified type (string, bool, int, float, list, dict)
    5. Validates the parsed values against the configuration

    Attributes:
        config (list):
            List of configuration dictionaries containing: name, type, default, and env_name keys.
        value_from_type (ValuesFromType):
            Instance for converting string values to appropriate types.
        values (dict):
            Dictionary of parsed environment variables mapped by configuration name.

    Raises:
        ValueError: If type conversion fails or configuration validation fails.

    Example:
        >>> import os
        >>> os.environ["DATABASE_URL"] = "postgresql://localhost"
        >>> os.environ["MAX_CONNECTIONS"] = "10"
        >>> config = [
        ...     {
        ...         "name": "db_url",
        ...         "type": "string",
        ...         "default": "sqlite:///:memory:",
        ...         "env_name": "DATABASE_URL"
        ...     },
        ...     {
        ...         "name": "max_conn",
        ...         "type": "int",
        ...         "default": 5,
        ...         "env_name": "MAX_CONNECTIONS"
        ...     }
        ... ]
        >>> parser = ParseFromEnvironment(config=config)
        >>> parser.get_values()
        {'db_url': 'postgresql://localhost', 'max_conn': 10}
    """

    def __init__(self, config: list) -> None:
        """Initialize the ParseFromEnvironment instance and parse environment variables.

        This constructor initializes the parser with a configuration list and immediately
        processes all environment variables. It performs validation on the parsed values
        to ensure they conform to the specified types.

        Args:
            config (list): List of configuration dictionaries. Each dictionary must contain:
                - name (str): The configuration parameter name.
                - type (str): The target type ('string', 'bool', 'int', 'float', 'list', 'dict').
                - default (any): The default value if environment variable is not found.
                - env_name (str): The environment variable name to look for.

        Raises:
            ValueError: If type conversion fails or if configuration validation fails.

        Example:
            >>> config = [
            ...     {"name": "api_key", "type": "string", "default": "", "env_name": "API_KEY"},
            ...     {"name": "debug", "type": "bool", "default": False, "env_name": "DEBUG"}
            ... ]
            >>> parser = ParseFromEnvironment(config=config)
        """
        self.config = config
        self.value_from_type = ValuesFromType(source_name="environment")

        self.__set_values()
        self.__check_values()

    def __set_values(self) -> None:
        """Parse environment variables and convert them to appropriate types.

        This private method iterates through the configuration items and retrieves
        the corresponding environment variable values. For each found environment
        variable, it converts the string value to the specified type using ValuesFromType.

        Only environment variables that are explicitly set are included in the results.
        Missing environment variables are skipped and not added to the values dictionary.

        The method stores the parsed values in the `self.values` instance attribute.

        Process:
            1. Initialize empty dictionary for results
            2. Iterate through each configuration item
            3. Get environment variable value using `os.environ.get(env_name)`
            4. If the value exists (not None):
               - Convert the string value to the specified type
               - Store in results dictionary under the configuration name
            5. Store results in `self.values`

        Returns:
            None

        Note:
            Missing environment variables are not added to the results. This is by design
            as the default value handling is performed at a higher level (in GetConfig).
        """
        ret_dict = {}
        for item in self.config:
            if item.get("env_name"):
                found = os.environ.get(item.get("env_name"))
                if found is not None:
                    ret_dict[item["name"]] = self.value_from_type.get_value(
                        value_type=item["type"],
                        value_found=found
                    )

        self.values = ret_dict

    def __check_values(self) -> None:
        """Validate the parsed environment variable values against the configuration.

        This private method validates that all parsed values:
        - Match their specified types
        - Conform to the accepted type system
        - Are valid for their configured types

        The validation is performed by the ValuesCheck class which ensures type safety
        and configuration compliance.

        Raises:
            ValueError: If any value fails validation (invalid type, missing required keys,
                       type mismatch, or unsupported type).

        Returns:
            None
        """
        ValuesCheck(config=self.config, values_found=self.values, info_string="environment values")

    def get_values(self) -> dict:
        """Return the parsed environment variables as a dictionary.

        This public method provides access to the parsed configuration values that were
        successfully retrieved from environment variables. Only environment variables
        that were actually set in the system are included in the returned dictionary.

        Returns:
            dict: Dictionary mapping configuration names to their parsed values from
                  environment variables. Format: {config_name: parsed_value}.
                  Only includes environment variables that were found and successfully
                  converted to their target types.

        Example:
            >>> import os
            >>> os.environ["PORT"] = "8080"
            >>> os.environ["TIMEOUT"] = "30"
            >>> config = [
            ...     {"name": "port", "type": "int", "default": 3000, "env_name": "PORT"},
            ...     {"name": "timeout", "type": "int", "default": 60, "env_name": "TIMEOUT"},
            ...     {"name": "host", "type": "string", "default": "localhost", "env_name": "HOST"}
            ... ]
            >>> parser = ParseFromEnvironment(config=config)
            >>> parser.get_values()
            {'port': 8080, 'timeout': 30}
            # Note: 'host' is not included because HOST environment variable is not set

        Returns:
            dict: Parsed environment variable values, or empty dict if no environment
                  variables were found for the configuration.
        """
        return self.values
Methods:
__check_values
__check_values() -> None

Validate the parsed environment variable values against the configuration.

This private method validates that all parsed values: - Match their specified types - Conform to the accepted type system - Are valid for their configured types

The validation is performed by the ValuesCheck class which ensures type safety and configuration compliance.

Raises:
  • ValueError –

    If any value fails validation (invalid type, missing required keys, type mismatch, or unsupported type).

Returns:
  • None –

    None

Source code in fejao_config_parser/src/parse_from/environment.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def __check_values(self) -> None:
    """Validate the parsed environment variable values against the configuration.

    This private method validates that all parsed values:
    - Match their specified types
    - Conform to the accepted type system
    - Are valid for their configured types

    The validation is performed by the ValuesCheck class which ensures type safety
    and configuration compliance.

    Raises:
        ValueError: If any value fails validation (invalid type, missing required keys,
                   type mismatch, or unsupported type).

    Returns:
        None
    """
    ValuesCheck(config=self.config, values_found=self.values, info_string="environment values")
__init__
__init__(config: list) -> None

Initialize the ParseFromEnvironment instance and parse environment variables.

This constructor initializes the parser with a configuration list and immediately processes all environment variables. It performs validation on the parsed values to ensure they conform to the specified types.

Parameters:
  • config (list) –

    List of configuration dictionaries. Each dictionary must contain: - name (str): The configuration parameter name. - type (str): The target type ('string', 'bool', 'int', 'float', 'list', 'dict'). - default (any): The default value if environment variable is not found. - env_name (str): The environment variable name to look for.

Raises:
  • ValueError –

    If type conversion fails or if configuration validation fails.

Example

config = [ ... {"name": "api_key", "type": "string", "default": "", "env_name": "API_KEY"}, ... {"name": "debug", "type": "bool", "default": False, "env_name": "DEBUG"} ... ] parser = ParseFromEnvironment(config=config)

Source code in fejao_config_parser/src/parse_from/environment.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def __init__(self, config: list) -> None:
    """Initialize the ParseFromEnvironment instance and parse environment variables.

    This constructor initializes the parser with a configuration list and immediately
    processes all environment variables. It performs validation on the parsed values
    to ensure they conform to the specified types.

    Args:
        config (list): List of configuration dictionaries. Each dictionary must contain:
            - name (str): The configuration parameter name.
            - type (str): The target type ('string', 'bool', 'int', 'float', 'list', 'dict').
            - default (any): The default value if environment variable is not found.
            - env_name (str): The environment variable name to look for.

    Raises:
        ValueError: If type conversion fails or if configuration validation fails.

    Example:
        >>> config = [
        ...     {"name": "api_key", "type": "string", "default": "", "env_name": "API_KEY"},
        ...     {"name": "debug", "type": "bool", "default": False, "env_name": "DEBUG"}
        ... ]
        >>> parser = ParseFromEnvironment(config=config)
    """
    self.config = config
    self.value_from_type = ValuesFromType(source_name="environment")

    self.__set_values()
    self.__check_values()
__set_values
__set_values() -> None

Parse environment variables and convert them to appropriate types.

This private method iterates through the configuration items and retrieves the corresponding environment variable values. For each found environment variable, it converts the string value to the specified type using ValuesFromType.

Only environment variables that are explicitly set are included in the results. Missing environment variables are skipped and not added to the values dictionary.

The method stores the parsed values in the self.values instance attribute.

Process
  1. Initialize empty dictionary for results
  2. Iterate through each configuration item
  3. Get environment variable value using os.environ.get(env_name)
  4. If the value exists (not None):
  5. Convert the string value to the specified type
  6. Store in results dictionary under the configuration name
  7. Store results in self.values
Returns:
  • None –

    None

Note

Missing environment variables are not added to the results. This is by design as the default value handling is performed at a higher level (in GetConfig).

Source code in fejao_config_parser/src/parse_from/environment.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
def __set_values(self) -> None:
    """Parse environment variables and convert them to appropriate types.

    This private method iterates through the configuration items and retrieves
    the corresponding environment variable values. For each found environment
    variable, it converts the string value to the specified type using ValuesFromType.

    Only environment variables that are explicitly set are included in the results.
    Missing environment variables are skipped and not added to the values dictionary.

    The method stores the parsed values in the `self.values` instance attribute.

    Process:
        1. Initialize empty dictionary for results
        2. Iterate through each configuration item
        3. Get environment variable value using `os.environ.get(env_name)`
        4. If the value exists (not None):
           - Convert the string value to the specified type
           - Store in results dictionary under the configuration name
        5. Store results in `self.values`

    Returns:
        None

    Note:
        Missing environment variables are not added to the results. This is by design
        as the default value handling is performed at a higher level (in GetConfig).
    """
    ret_dict = {}
    for item in self.config:
        if item.get("env_name"):
            found = os.environ.get(item.get("env_name"))
            if found is not None:
                ret_dict[item["name"]] = self.value_from_type.get_value(
                    value_type=item["type"],
                    value_found=found
                )

    self.values = ret_dict
get_values
get_values() -> dict

Return the parsed environment variables as a dictionary.

This public method provides access to the parsed configuration values that were successfully retrieved from environment variables. Only environment variables that were actually set in the system are included in the returned dictionary.

Returns:
  • dict( dict ) –

    Dictionary mapping configuration names to their parsed values from environment variables. Format: {config_name: parsed_value}. Only includes environment variables that were found and successfully converted to their target types.

Example

import os os.environ["PORT"] = "8080" os.environ["TIMEOUT"] = "30" config = [ ... {"name": "port", "type": "int", "default": 3000, "env_name": "PORT"}, ... {"name": "timeout", "type": "int", "default": 60, "env_name": "TIMEOUT"}, ... {"name": "host", "type": "string", "default": "localhost", "env_name": "HOST"} ... ] parser = ParseFromEnvironment(config=config) parser.get_values() {'port': 8080, 'timeout': 30}

Note: 'host' is not included because HOST environment variable is not set
Returns:
  • dict( dict ) –

    Parsed environment variable values, or empty dict if no environment variables were found for the configuration.

Source code in fejao_config_parser/src/parse_from/environment.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def get_values(self) -> dict:
    """Return the parsed environment variables as a dictionary.

    This public method provides access to the parsed configuration values that were
    successfully retrieved from environment variables. Only environment variables
    that were actually set in the system are included in the returned dictionary.

    Returns:
        dict: Dictionary mapping configuration names to their parsed values from
              environment variables. Format: {config_name: parsed_value}.
              Only includes environment variables that were found and successfully
              converted to their target types.

    Example:
        >>> import os
        >>> os.environ["PORT"] = "8080"
        >>> os.environ["TIMEOUT"] = "30"
        >>> config = [
        ...     {"name": "port", "type": "int", "default": 3000, "env_name": "PORT"},
        ...     {"name": "timeout", "type": "int", "default": 60, "env_name": "TIMEOUT"},
        ...     {"name": "host", "type": "string", "default": "localhost", "env_name": "HOST"}
        ... ]
        >>> parser = ParseFromEnvironment(config=config)
        >>> parser.get_values()
        {'port': 8080, 'timeout': 30}
        # Note: 'host' is not included because HOST environment variable is not set

    Returns:
        dict: Parsed environment variable values, or empty dict if no environment
              variables were found for the configuration.
    """
    return self.values