# Confingo
Confingo is a Python package that simplifies configuration management using YAML and JSON files. It allows you to load, manipulate, and serialize configurations with ease, providing both attribute-style and dictionary-style access to configuration parameters.
## Features
- **Load Configurations**:
- From YAML files.
- From JSON files.
- From strings, bytes, or file-like objects.
- **Access Configuration Parameters**:
- Using dot notation (attribute-style access).
- Using key access (dictionary-style access).
- **Programmatically Define and Manipulate Configurations**:
- Create nested configurations effortlessly.
- Dynamically add, modify, or delete configuration parameters.
- **Serialization and Deserialization**:
- Serialize configurations to YAML and JSON formats.
- Deserialize configurations from YAML and JSON formats.
- Dump serialized configurations to file-like streams.
- **Delete Configuration Parameters**:
- Remove configuration parameters using both attribute-style and dictionary-style access.
## Installation
You can install Confingo via pip:
```bash
pip install confingo
```
## Requirements
- Python >= 3.9
- PyYAML >= 5.4
## Usage
### Loading a Configuration File
Confingo supports loading configurations from both YAML and JSON files.
#### Loading from a YAML File
```python
from confingo import load_config
config = load_config('config.yaml') # Automatically detects YAML based on file extension
print(config.database.host)
print(config['database']['host'])
```
#### Loading from a JSON File
```python
from confingo import load_config_from_json
config = load_config_from_json('config.json')
print(config.server.host)
print(config['server']['host'])
```
### Loading Configuration from Strings or File-Like Objects
You can also load configurations from strings, bytes, or file-like objects.
#### From a YAML String
```python
from confingo import load_config_from_content
yaml_content = """
database:
host: localhost
port: 5432
"""
config = load_config_from_content(yaml_content)
print(config.database.host)
```
#### From a JSON String
```python
from confingo import load_config_from_content
json_content = """
{
"server": {
"host": "127.0.0.1",
"port": 8080
}
}
"""
config = load_config_from_content(json_content)
print(config.server.host)
```
#### From a File-Like Object
```python
from confingo import load_config_from_content
from io import StringIO
yaml_content = """
database:
host: localhost
port: 5432
"""
file_like_object = StringIO(yaml_content)
config = load_config_from_content(file_like_object)
print(config.database.port)
```
### Programmatically Defining Configurations
You can create configurations programmatically without using a YAML or JSON file.
```python
from confingo import Config
config = Config()
config.database = Config()
config.database.host = 'localhost'
config.database.port = 5432
config.server = Config()
config.server.host = '127.0.0.1'
config.server.port = 8080
print(config.database.host) # Outputs: localhost
print(config['server']['port']) # Outputs: 8080
```
### Accessing Configuration Parameters
Confingo allows you to access configuration parameters using both attribute and key access.
```python
# Attribute access
print(config.database.host)
# Key access
print(config['database']['host'])
```
### Deleting Configuration Parameters
Confingo provides methods to delete configuration parameters using both attribute-style and dictionary-style access.
#### Deleting via Attribute Access
```python
from confingo import Config
config = Config()
config.database = Config()
config.database.host = 'localhost'
config.database.port = 5432
# Delete an attribute
del config.database.port
# Verify deletion
assert not hasattr(config.database, 'port')
assert 'port' not in config.database
```
#### Deleting via Dictionary Access
```python
from confingo import Config
config = Config()
config['server'] = Config()
config['server']['host'] = '127.0.0.1'
config['server']['port'] = 8080
# Delete an item
del config['server']['port']
# Verify deletion
assert 'port' not in config.server
assert not hasattr(config.server, 'port')
```
### Serialization and Deserialization
Confingo provides methods to serialize and deserialize configurations to and from YAML and JSON formats.
#### Serialize to YAML
```python
yaml_str = config.to_yaml()
print(yaml_str)
```
#### Dump YAML to a File
```python
with open('output.yaml', 'w') as f:
config.dump_yaml(f)
```
#### Serialize to JSON
```python
json_str = config.to_json(indent=2)
print(json_str)
```
#### Dump JSON to a File
```python
with open('output.json', 'w') as f:
config.dump_json(f, indent=2)
```
### Example
Given a `config.yaml` file:
```yaml
database:
host: localhost
port: 5432
users:
- name: admin
role: superuser
- name: guest
role: read-only
server:
host: 127.0.0.1
port: 8080
```
You can load and access the configuration as follows:
```python
from confingo import load_config
config = load_config('config.yaml')
# Access database host
print(config.database.host) # Outputs: localhost
# Access server port
print(config.server.port) # Outputs: 8080
# List all users
for user in config.database.users:
print(f"{user.name} - {user.role}")
```
#### Output:
```
localhost
8080
admin - superuser
guest - read-only
```
### Serialization Example
```python
from confingo import load_config
config = load_config('config.yaml')
# Serialize to YAML string
yaml_output = config.to_yaml()
print(yaml_output)
# Serialize to JSON string
json_output = config.to_json(indent=2)
print(json_output)
# Dump serialized YAML to a file
with open('serialized_config.yaml', 'w') as f:
config.dump_yaml(f)
# Dump serialized JSON to a file
with open('serialized_config.json', 'w') as f:
config.dump_json(f, indent=2)
```
## API Reference
### `Config` Class
A class representing a configuration object that supports both dictionary-style and attribute-style access to its elements.
Inherits from `argparse.Namespace` and `dict` to provide a flexible configuration management solution, allowing nested configurations, attribute access, and YAML/JSON-based serialization and deserialization.
#### Methods
- **`to_dict()`**: Converts the `Config` object to a native Python dictionary.
```python
config_dict = config.to_dict()
```
- **`to_yaml(**kwargs)`**: Serializes the `Config` object to a YAML-formatted string.
```python
yaml_str = config.to_yaml()
```
- **`dump_yaml(stream: IO[Any], **kwargs)`**: Writes the `Config` object as YAML to a file-like stream.
```python
with open('output.yaml', 'w') as f:
config.dump_yaml(f)
```
- **`to_json(**kwargs)`**: Serializes the `Config` object to a JSON-formatted string.
```python
json_str = config.to_json(indent=2)
```
- **`dump_json(stream: IO[Any], **kwargs)`**: Writes the `Config` object as JSON to a file-like stream.
```python
with open('output.json', 'w') as f:
config.dump_json(f, indent=2)
```
- **`__delattr__(key: str) -> None`**: Deletes an attribute from the `Config` object, removing it from both attribute-style and dictionary-style access.
```python
del config.attribute_name
```
- **`__delitem__(key: str) -> None`**: Deletes an item from the `Config` object using dictionary-style access, removing it from both attribute-style and dictionary-style access.
```python
del config['item_name']
```
### Loading Functions
- **`load_config(path: Union[str, Path]) -> Config`**: Loads a YAML or JSON configuration file from a given file path and returns it as a `Config` object.
```python
config = load_config('config.yaml')
```
- **`load_config_from_content(stream: Union[str, bytes, IO[Any]]) -> Config`**: Loads a YAML or JSON configuration from various input types (string, bytes, or file-like object) and returns it as a `Config` object.
```python
config = load_config_from_content(yaml_content)
config = load_config_from_content(json_content)
```
## Testing
Confingo includes a comprehensive test suite to ensure reliability and correctness. The tests cover configuration loading, access methods, serialization, deletion, and error handling.
### Running the Tests
To run the tests, ensure you have `pytest` installed and execute:
```bash
pytest
```
This command will automatically discover and run all the tests defined in your test suite.
### Test Coverage
The test suite covers the following aspects:
- **Attribute and Dictionary Access**: Ensures both access styles work seamlessly.
- **Loading Configurations**: From YAML files, JSON files, strings, bytes, and file-like objects.
- **Serialization**: To YAML and JSON strings and files, including empty and complex structures.
- **Deserialization**: Ensures loaded configurations match expected structures.
- **Deletion**: Removing attributes and items via both `delattr` and `del` operations.
- **Edge Cases**: Handling empty configurations and deeply nested structures.
- **Error Handling**: Invalid keys and data nodes correctly raise exceptions.
- **Representation**: Ensures `__str__` and `__repr__` provide accurate outputs.
## License
Confingo is licensed under the [MIT License](LICENSE).
## Author
Ben Elfner
Raw data
{
"_id": null,
"home_page": "https://github.com/belfner/confingo",
"name": "confingo",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.9",
"maintainer_email": null,
"keywords": "configuration, yaml, config management",
"author": "Ben Elfner",
"author_email": "belfner@belfner.com",
"download_url": "https://files.pythonhosted.org/packages/db/5b/13c6fb24dce59170844febf67465e7f54a5254c6b71bbe27666b2f369189/confingo-1.0.1.tar.gz",
"platform": null,
"description": "# Confingo\n\nConfingo is a Python package that simplifies configuration management using YAML and JSON files. It allows you to load, manipulate, and serialize configurations with ease, providing both attribute-style and dictionary-style access to configuration parameters.\n\n## Features\n\n- **Load Configurations**:\n - From YAML files.\n - From JSON files.\n - From strings, bytes, or file-like objects.\n- **Access Configuration Parameters**:\n - Using dot notation (attribute-style access).\n - Using key access (dictionary-style access).\n- **Programmatically Define and Manipulate Configurations**:\n - Create nested configurations effortlessly.\n - Dynamically add, modify, or delete configuration parameters.\n- **Serialization and Deserialization**:\n - Serialize configurations to YAML and JSON formats.\n - Deserialize configurations from YAML and JSON formats.\n - Dump serialized configurations to file-like streams.\n- **Delete Configuration Parameters**:\n - Remove configuration parameters using both attribute-style and dictionary-style access.\n\n## Installation\n\nYou can install Confingo via pip:\n\n```bash\npip install confingo\n```\n\n## Requirements\n\n- Python >= 3.9\n- PyYAML >= 5.4\n\n## Usage\n\n### Loading a Configuration File\n\nConfingo supports loading configurations from both YAML and JSON files.\n\n#### Loading from a YAML File\n\n```python\nfrom confingo import load_config\n\nconfig = load_config('config.yaml') # Automatically detects YAML based on file extension\nprint(config.database.host)\nprint(config['database']['host'])\n```\n\n#### Loading from a JSON File\n\n```python\nfrom confingo import load_config_from_json\n\nconfig = load_config_from_json('config.json')\nprint(config.server.host)\nprint(config['server']['host'])\n```\n\n### Loading Configuration from Strings or File-Like Objects\n\nYou can also load configurations from strings, bytes, or file-like objects.\n\n#### From a YAML String\n\n```python\nfrom confingo import load_config_from_content\n\nyaml_content = \"\"\"\ndatabase:\n host: localhost\n port: 5432\n\"\"\"\nconfig = load_config_from_content(yaml_content)\nprint(config.database.host)\n```\n\n#### From a JSON String\n\n```python\nfrom confingo import load_config_from_content\n\njson_content = \"\"\"\n{\n \"server\": {\n \"host\": \"127.0.0.1\",\n \"port\": 8080\n }\n}\n\"\"\"\nconfig = load_config_from_content(json_content)\nprint(config.server.host)\n```\n\n#### From a File-Like Object\n\n```python\nfrom confingo import load_config_from_content\nfrom io import StringIO\n\nyaml_content = \"\"\"\ndatabase:\n host: localhost\n port: 5432\n\"\"\"\nfile_like_object = StringIO(yaml_content)\nconfig = load_config_from_content(file_like_object)\nprint(config.database.port)\n```\n\n### Programmatically Defining Configurations\n\nYou can create configurations programmatically without using a YAML or JSON file.\n\n```python\nfrom confingo import Config\n\nconfig = Config()\n\nconfig.database = Config()\nconfig.database.host = 'localhost'\nconfig.database.port = 5432\n\nconfig.server = Config()\nconfig.server.host = '127.0.0.1'\nconfig.server.port = 8080\n\nprint(config.database.host) # Outputs: localhost\nprint(config['server']['port']) # Outputs: 8080\n```\n\n### Accessing Configuration Parameters\n\nConfingo allows you to access configuration parameters using both attribute and key access.\n\n```python\n# Attribute access\nprint(config.database.host)\n\n# Key access\nprint(config['database']['host'])\n```\n\n### Deleting Configuration Parameters\n\nConfingo provides methods to delete configuration parameters using both attribute-style and dictionary-style access.\n\n#### Deleting via Attribute Access\n\n```python\nfrom confingo import Config\n\nconfig = Config()\nconfig.database = Config()\nconfig.database.host = 'localhost'\nconfig.database.port = 5432\n\n# Delete an attribute\ndel config.database.port\n\n# Verify deletion\nassert not hasattr(config.database, 'port')\nassert 'port' not in config.database\n```\n\n#### Deleting via Dictionary Access\n\n```python\nfrom confingo import Config\n\nconfig = Config()\nconfig['server'] = Config()\nconfig['server']['host'] = '127.0.0.1'\nconfig['server']['port'] = 8080\n\n# Delete an item\ndel config['server']['port']\n\n# Verify deletion\nassert 'port' not in config.server\nassert not hasattr(config.server, 'port')\n```\n\n### Serialization and Deserialization\n\nConfingo provides methods to serialize and deserialize configurations to and from YAML and JSON formats.\n\n#### Serialize to YAML\n\n```python\nyaml_str = config.to_yaml()\nprint(yaml_str)\n```\n\n#### Dump YAML to a File\n\n```python\nwith open('output.yaml', 'w') as f:\n config.dump_yaml(f)\n```\n\n#### Serialize to JSON\n\n```python\njson_str = config.to_json(indent=2)\nprint(json_str)\n```\n\n#### Dump JSON to a File\n\n```python\nwith open('output.json', 'w') as f:\n config.dump_json(f, indent=2)\n```\n\n### Example\n\nGiven a `config.yaml` file:\n\n```yaml\ndatabase:\n host: localhost\n port: 5432\n users:\n - name: admin\n role: superuser\n - name: guest\n role: read-only\nserver:\n host: 127.0.0.1\n port: 8080\n```\n\nYou can load and access the configuration as follows:\n\n```python\nfrom confingo import load_config\n\nconfig = load_config('config.yaml')\n\n# Access database host\nprint(config.database.host) # Outputs: localhost\n\n# Access server port\nprint(config.server.port) # Outputs: 8080\n\n# List all users\nfor user in config.database.users:\n print(f\"{user.name} - {user.role}\")\n```\n\n#### Output:\n\n```\nlocalhost\n8080\nadmin - superuser\nguest - read-only\n```\n\n### Serialization Example\n\n```python\nfrom confingo import load_config\n\nconfig = load_config('config.yaml')\n\n# Serialize to YAML string\nyaml_output = config.to_yaml()\nprint(yaml_output)\n\n# Serialize to JSON string\njson_output = config.to_json(indent=2)\nprint(json_output)\n\n# Dump serialized YAML to a file\nwith open('serialized_config.yaml', 'w') as f:\n config.dump_yaml(f)\n\n# Dump serialized JSON to a file\nwith open('serialized_config.json', 'w') as f:\n config.dump_json(f, indent=2)\n```\n\n## API Reference\n\n### `Config` Class\n\nA class representing a configuration object that supports both dictionary-style and attribute-style access to its elements.\n\nInherits from `argparse.Namespace` and `dict` to provide a flexible configuration management solution, allowing nested configurations, attribute access, and YAML/JSON-based serialization and deserialization.\n\n#### Methods\n\n- **`to_dict()`**: Converts the `Config` object to a native Python dictionary.\n \n ```python\n config_dict = config.to_dict()\n ```\n \n- **`to_yaml(**kwargs)`**: Serializes the `Config` object to a YAML-formatted string.\n \n ```python\n yaml_str = config.to_yaml()\n ```\n \n- **`dump_yaml(stream: IO[Any], **kwargs)`**: Writes the `Config` object as YAML to a file-like stream.\n \n ```python\n with open('output.yaml', 'w') as f:\n config.dump_yaml(f)\n ```\n \n- **`to_json(**kwargs)`**: Serializes the `Config` object to a JSON-formatted string.\n \n ```python\n json_str = config.to_json(indent=2)\n ```\n \n- **`dump_json(stream: IO[Any], **kwargs)`**: Writes the `Config` object as JSON to a file-like stream.\n \n ```python\n with open('output.json', 'w') as f:\n config.dump_json(f, indent=2)\n ```\n \n- **`__delattr__(key: str) -> None`**: Deletes an attribute from the `Config` object, removing it from both attribute-style and dictionary-style access.\n \n ```python\n del config.attribute_name\n ```\n \n- **`__delitem__(key: str) -> None`**: Deletes an item from the `Config` object using dictionary-style access, removing it from both attribute-style and dictionary-style access.\n \n ```python\n del config['item_name']\n ```\n\n### Loading Functions\n\n- **`load_config(path: Union[str, Path]) -> Config`**: Loads a YAML or JSON configuration file from a given file path and returns it as a `Config` object.\n \n ```python\n config = load_config('config.yaml')\n ```\n \n- **`load_config_from_content(stream: Union[str, bytes, IO[Any]]) -> Config`**: Loads a YAML or JSON configuration from various input types (string, bytes, or file-like object) and returns it as a `Config` object.\n \n ```python\n config = load_config_from_content(yaml_content)\n config = load_config_from_content(json_content)\n ```\n \n\n## Testing\n\nConfingo includes a comprehensive test suite to ensure reliability and correctness. The tests cover configuration loading, access methods, serialization, deletion, and error handling.\n\n### Running the Tests\n\nTo run the tests, ensure you have `pytest` installed and execute:\n\n```bash\npytest\n```\n\nThis command will automatically discover and run all the tests defined in your test suite.\n\n### Test Coverage\n\nThe test suite covers the following aspects:\n\n- **Attribute and Dictionary Access**: Ensures both access styles work seamlessly.\n- **Loading Configurations**: From YAML files, JSON files, strings, bytes, and file-like objects.\n- **Serialization**: To YAML and JSON strings and files, including empty and complex structures.\n- **Deserialization**: Ensures loaded configurations match expected structures.\n- **Deletion**: Removing attributes and items via both `delattr` and `del` operations.\n- **Edge Cases**: Handling empty configurations and deeply nested structures.\n- **Error Handling**: Invalid keys and data nodes correctly raise exceptions.\n- **Representation**: Ensures `__str__` and `__repr__` provide accurate outputs.\n\n## License\n\nConfingo is licensed under the [MIT License](LICENSE).\n\n## Author\n\nBen Elfner\n",
"bugtrack_url": null,
"license": null,
"summary": "A Python package for easy configuration management using YAML files.",
"version": "1.0.1",
"project_urls": {
"Homepage": "https://github.com/belfner/confingo"
},
"split_keywords": [
"configuration",
" yaml",
" config management"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "c4d3e1458dc3032f9a13550d89b3c2e82e981debd7721a3076a3674f7a79931e",
"md5": "2ea7fbdfcc9131f90c9942254470f1e9",
"sha256": "fff50c736367a85884a1ec1f62ba24c9016aaee63b3396fdf38cb78b11289a46"
},
"downloads": -1,
"filename": "confingo-1.0.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "2ea7fbdfcc9131f90c9942254470f1e9",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9",
"size": 7441,
"upload_time": "2024-10-25T22:23:49",
"upload_time_iso_8601": "2024-10-25T22:23:49.868056Z",
"url": "https://files.pythonhosted.org/packages/c4/d3/e1458dc3032f9a13550d89b3c2e82e981debd7721a3076a3674f7a79931e/confingo-1.0.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "db5b13c6fb24dce59170844febf67465e7f54a5254c6b71bbe27666b2f369189",
"md5": "baf4477fe6074daecb3c7139c9093f26",
"sha256": "502095139ec7ba8d10ea63aed591bdf5fb84b6bb05bf17a0e19a798e915f281b"
},
"downloads": -1,
"filename": "confingo-1.0.1.tar.gz",
"has_sig": false,
"md5_digest": "baf4477fe6074daecb3c7139c9093f26",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9",
"size": 10143,
"upload_time": "2024-10-25T22:23:51",
"upload_time_iso_8601": "2024-10-25T22:23:51.351973Z",
"url": "https://files.pythonhosted.org/packages/db/5b/13c6fb24dce59170844febf67465e7f54a5254c6b71bbe27666b2f369189/confingo-1.0.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-10-25 22:23:51",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "belfner",
"github_project": "confingo",
"github_not_found": true,
"lcname": "confingo"
}