# Config2Class: A Tool to Generate Python Dataclasses from Configuration Files
   [](https://coveralls.io/github/RobinU434/Config2Class) 
## Introduction
Config2Code is a Python tool designed to streamline the process of converting configuration files (YAML or JSON or TOML) into Python dataclasses. By automating the generation of dataclasses, you can improve code readability, maintainability, and type safety.
## Installation
You can install Config2Code using pip:
```bash
pip install config2code
```
## Usage
### Basic Example
1. **Prepare your configuration file:**
Create a YAML or JSON file containing your configuration data. Here's an example YAML file:
```yaml
DatabaseConfig:
host: localhost
port: 5432
user: myuser
password: mypassword
```
2. **Run the tool:**
Use the `config2code` command-line interface to convert the configuration file:
```bash
config2code to-code --input input.yaml --output output.py
```
This will generate a Python file `output.py` containing a dataclass representing the configuration:
```python
from dataclasses import dataclass
@dataclass
class DatabaseConfig:
host: str
port: int
user: str
password: str
```
### Placeholder Example
Sometimes you put redundant data in your config file because it is more convenient to only move parts of the config further down the road. Examples could be a machine learning pipeline where you have parameters for your dataset and model which can have redundant values. To counter the problem of always changing multiple values at once in your config we introduce **placeholder**. A placeholder is a path packed into a token `${<path-in-config>}` which points to a value you want to insert automatically into your loaded config file. This path starts always at the yaml root and ends at the value to insert.
```yaml
pipeline:
dataset:
x_dim: 42
y_dim: 5
batch_size: 128
shuffle: True
model:
input_dim: ${pipeline.dataset.x_dim}
output_dim: ${pipeline.dataset.y_dim}
activation_func: ReLU
learning_rate: 0.0001
```
Here we use the API of [OmegaConf](https://omegaconf.readthedocs.io/en/2.3_branch/). Therefor you are allowed to use all kinds of funny stuff like custom evaluators or missing value imputation or merging config files from multiple files or .... .
Please note for the last one is no tested feature for merging configs from multiple files into one big structured config.
### Hydra Integration
Additionally we support now a Hydra integration where provide functions to add the hydra ArgumentParser to your custom parser.
> **_Note:_** Please note this feature is still underdevelopment. Therefor please be careful while merging those two argument parser and setup the wrapper function. A rough example can be examined [here](usage_examples/hydra_integration.py)
### Service
This service monitors the requested configuration file. If the services detects changes in the file it will automatically write those changes into the specified `output.py`.
You can start the service for example with:
```bash
config2code service-start --input input.yaml --output output.py
```
To stop it you can stop all with
```bash
config2code stop-all
```
### Use Config in Code
After you created your python config you can easily use as follows:
```python
from output import DatabaseConfig
config = DatabaseConfig.from_file("input.yaml")
# access config field with dot operator
config.host
```
This is different to a normal `DictConfig` from OmegaConf because this supports code completion in your coding environment.
## Key Features
* **Supports YAML, JSON and TOML:** Easily convert both formats.
* **Automatic dataclass generation:** Generates well-structured dataclasses.
* **Nested configuration support:** Handles nested structures in your configuration files.
* **Type inference:** Infers types for fields based on their values.
* **Placeholder:** Choose which values in your config file are dependent on others
## Additional Considerations
* **Complex data structures:** For more complex data structures, consider using custom type hints or additional configuration options.
* **Error handling:** The tool includes basic error handling for file loading and parsing.
* **Future enhancements:** We plan to add support for additional file formats, advanced type inference, and more customization options.
## Features to expand
* [ ] add VS Code extension (create new file on config file save)
* [ ] add renaming feature from config to code (renaming a field in the config file should resolve in renaming a field in the code
* [ ] expand token feature so you can access memeber of a list `{{<path>.<to>.<element>[<index>]}}`
## Contributing
We welcome contributions to improve Config2Code. Feel free to fork the repository, make changes, and submit a pull request.
**License**
This project is licensed under the MIT License.
Raw data
{
"_id": null,
"home_page": "https://github.com/RobinU434/Config2Class",
"name": "config2class",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.10",
"maintainer_email": null,
"keywords": "autocomplete, structured-config, code-generation, configuration",
"author": "Robin Uhrich",
"author_email": "robin.uhrich@gmx.de",
"download_url": "https://files.pythonhosted.org/packages/73/73/fc250401c3afe35749848caddd950fdb6cb56ab98f8f2ed87441e1f2b6b8/config2class-0.3.1.tar.gz",
"platform": null,
"description": "# Config2Class: A Tool to Generate Python Dataclasses from Configuration Files\n\n   [](https://coveralls.io/github/RobinU434/Config2Class) \n\n## Introduction\n\nConfig2Code is a Python tool designed to streamline the process of converting configuration files (YAML or JSON or TOML) into Python dataclasses. By automating the generation of dataclasses, you can improve code readability, maintainability, and type safety.\n\n## Installation\n\nYou can install Config2Code using pip:\n\n```bash\npip install config2code\n```\n\n## Usage\n\n### Basic Example\n\n1. **Prepare your configuration file:**\n Create a YAML or JSON file containing your configuration data. Here's an example YAML file:\n\n ```yaml\n DatabaseConfig:\n host: localhost\n port: 5432\n user: myuser\n password: mypassword\n ```\n2. **Run the tool:**\n Use the `config2code` command-line interface to convert the configuration file:\n\n ```bash\n config2code to-code --input input.yaml --output output.py\n ```\n\n This will generate a Python file `output.py` containing a dataclass representing the configuration:\n\n ```python\n from dataclasses import dataclass\n\n @dataclass\n class DatabaseConfig:\n host: str\n port: int\n user: str\n password: str\n ```\n\n### Placeholder Example\n\nSometimes you put redundant data in your config file because it is more convenient to only move parts of the config further down the road. Examples could be a machine learning pipeline where you have parameters for your dataset and model which can have redundant values. To counter the problem of always changing multiple values at once in your config we introduce **placeholder**. A placeholder is a path packed into a token `${<path-in-config>}` which points to a value you want to insert automatically into your loaded config file. This path starts always at the yaml root and ends at the value to insert.\n\n```yaml\n pipeline:\n dataset: \n x_dim: 42\n y_dim: 5\n batch_size: 128\n shuffle: True\n model:\n input_dim: ${pipeline.dataset.x_dim}\n output_dim: ${pipeline.dataset.y_dim}\n activation_func: ReLU\n learning_rate: 0.0001\n```\n\nHere we use the API of [OmegaConf](https://omegaconf.readthedocs.io/en/2.3_branch/). Therefor you are allowed to use all kinds of funny stuff like custom evaluators or missing value imputation or merging config files from multiple files or .... . \nPlease note for the last one is no tested feature for merging configs from multiple files into one big structured config. \n\n### Hydra Integration\n\nAdditionally we support now a Hydra integration where provide functions to add the hydra ArgumentParser to your custom parser.\n> **_Note:_** Please note this feature is still underdevelopment. Therefor please be careful while merging those two argument parser and setup the wrapper function. A rough example can be examined [here](usage_examples/hydra_integration.py)\n\n### Service\n\nThis service monitors the requested configuration file. If the services detects changes in the file it will automatically write those changes into the specified `output.py`.\nYou can start the service for example with:\n\n```bash\nconfig2code service-start --input input.yaml --output output.py\n```\n\nTo stop it you can stop all with\n\n```bash\nconfig2code stop-all\n```\n\n### Use Config in Code\n\nAfter you created your python config you can easily use as follows:\n\n```python\nfrom output import DatabaseConfig\n\nconfig = DatabaseConfig.from_file(\"input.yaml\")\n# access config field with dot operator\nconfig.host\n```\n\nThis is different to a normal `DictConfig` from OmegaConf because this supports code completion in your coding environment. \n\n## Key Features\n\n* **Supports YAML, JSON and TOML:** Easily convert both formats.\n* **Automatic dataclass generation:** Generates well-structured dataclasses.\n* **Nested configuration support:** Handles nested structures in your configuration files.\n* **Type inference:** Infers types for fields based on their values.\n* **Placeholder:** Choose which values in your config file are dependent on others\n\n## Additional Considerations\n\n* **Complex data structures:** For more complex data structures, consider using custom type hints or additional configuration options.\n* **Error handling:** The tool includes basic error handling for file loading and parsing.\n* **Future enhancements:** We plan to add support for additional file formats, advanced type inference, and more customization options.\n\n## Features to expand\n\n* [ ] add VS Code extension (create new file on config file save)\n* [ ] add renaming feature from config to code (renaming a field in the config file should resolve in renaming a field in the code\n* [ ] expand token feature so you can access memeber of a list `{{<path>.<to>.<element>[<index>]}}`\n\n## Contributing\n\nWe welcome contributions to improve Config2Code. Feel free to fork the repository, make changes, and submit a pull request.\n\n**License**\n\nThis project is licensed under the MIT License.\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Config2Code simplifies configuration management by automatically generating Python dataclasses from YAML or JSON files. This tool enhances code readability, maintainability, and type safety, saving you time and effort.",
"version": "0.3.1",
"project_urls": {
"Homepage": "https://github.com/RobinU434/Config2Class",
"Repository": "https://github.com/RobinU434/Config2Class"
},
"split_keywords": [
"autocomplete",
" structured-config",
" code-generation",
" configuration"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "297e9698e5710d8be8a15be3eb1628d889eb9127e5b5c658ef54d9b52ffe1e60",
"md5": "db17b388d1abbbf8d02b73200a9ce048",
"sha256": "c146ff202c248e1d0bca9867af1de539faa01a1a18bfc82e7fadec306659f608"
},
"downloads": -1,
"filename": "config2class-0.3.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "db17b388d1abbbf8d02b73200a9ce048",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.10",
"size": 20390,
"upload_time": "2025-01-11T15:20:56",
"upload_time_iso_8601": "2025-01-11T15:20:56.373557Z",
"url": "https://files.pythonhosted.org/packages/29/7e/9698e5710d8be8a15be3eb1628d889eb9127e5b5c658ef54d9b52ffe1e60/config2class-0.3.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "7373fc250401c3afe35749848caddd950fdb6cb56ab98f8f2ed87441e1f2b6b8",
"md5": "024b0bc62080ee89239e41ab52f6a24e",
"sha256": "44ccb744b31416651179e66fdd524475b4b8e8fc5b9e4e418c49576621384333"
},
"downloads": -1,
"filename": "config2class-0.3.1.tar.gz",
"has_sig": false,
"md5_digest": "024b0bc62080ee89239e41ab52f6a24e",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.10",
"size": 15823,
"upload_time": "2025-01-11T15:21:00",
"upload_time_iso_8601": "2025-01-11T15:21:00.142455Z",
"url": "https://files.pythonhosted.org/packages/73/73/fc250401c3afe35749848caddd950fdb6cb56ab98f8f2ed87441e1f2b6b8/config2class-0.3.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-01-11 15:21:00",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "RobinU434",
"github_project": "Config2Class",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "config2class"
}