bentoudev.dataclass


Namebentoudev.dataclass JSON
Version 1.6.0 PyPI version JSON
download
home_page
SummaryYaml to dataclass loader
upload_time2024-02-15 21:43:35
maintainer
docs_urlNone
authorBentouDev
requires_python>=3.7
license
keywords yaml dataclass
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Bentoudev.dataclass

[![CI (on push)](https://github.com/BentouDev/Bentoudev.dataclass/actions/workflows/python-ci.yml/badge.svg)](https://github.com/BentouDev/Bentoudev.dataclass/actions/workflows/python-ci.yml) [![PyPI version](https://badge.fury.io/py/bentoudev.dataclass.svg)](https://badge.fury.io/py/bentoudev.dataclass)

Yaml to dataclass loader. Validates objects based on type information.

Supports folowing types:
- classes marked as dataclass (from ``dataclasses``)
- int, str, float, list
- Enum (from ``enum``)
- Optional, List, Dict, Union (from ``typing``)
- forward references to not yet known types (see example), including self-referencing

## Install
```sh
pip install bentoudev.dataclass
```

## Documentation
Work in progress, for now, check out examples below or browse the source code.

## Example

```python
@dataclass
class Person:
    name: str
    age: int
    money: float

yaml_content = (
    'name: John\n'
    'age: 30\n'
    'money: 400.50'
)

obj = load_yaml_dataclass(Person, 'Person', yaml_content)

assert obj.name == 'John'
```

### Inline loaders
If you need to load complex class from a single value (like string), you can use ``@inline_loader`` attribute

```python
import bentoudev.dataclass.yaml_loader
import bentoudev.dataclass.base

@dataclass
@inline_loader(source_type=str, field_name='name')
class ObjFromStr:
    name: str
    foo: int
    bar: float

@dataclass
class Container:
    value: ObjFromStr

obj = load_yaml_dataclass(Container, 'pretty file name', 'value: ThisIsMyName')

assert obj.value.name == 'ThisIsMyName'
```
### Forward references to external types
Sometimes you might want to load dataclass that forward references foreign types, from other modules, in form of a string. In order to support such types, loader must be supplied with list of them.
```python

@dataclass
class MyDataclass:
    foo: Optional['my_namespace.project.model.my_ext_dataclass']

local_types = base.get_types_from_modules([__name__, 'my_namespace.project.model.my_ext_dataclass'])

my_obj: MyDataclass = yaml_loader.load_yaml_dataclass(MyDataclass, 'pretty file name', yaml_content, ext_types=local_types)
```

### Self referencing types
Additionaly to external types, self referencing is also supported

```python
from dataclasses import dataclass
import bentoudev.dataclass.yaml_loader as yaml_loader

@dataclass
class MyDataclass:
    my_string: str
    self_nested: Optional['MyDataclass']
    list_of_sth: List[str]
    user_data: Dict[str, str]

yaml_content = (
    'my_string: foo\n'
    'self_nested:\n'
    '  my_string: bar\n'
    '  list_of_sth: inline_value\n'
    'list_of_sth:\n'
    '- first\n'
    '- second\n'
    'user_data:\n'
    '  anything: goes'
)

my_obj: MyDataclass = yaml_loader.load_yaml_dataclass(MyDataclass, 'pretty file name', yaml_content)
```
### Remember lines
Additional information about source from which obj/field was loaded can be enabled by using ``@track_source`` attribute, or setting ``always_track_source`` parameter to True (disabled by default, but recomended). Such information is then used to print prettier errors in ``DataclassLoadError``.

```python
class EKind(Enum):
    FIRST = 1
    SECOND = 2

@dataclass
class SomeClass:
    kind: EKind

try:
    obj =  yaml_loader.load_yaml_dataclass(SomeClass, '[SomeClass] my_file.yml', 'kind: THIRD', always_track_source=True)
except DataclassLoadError as err:
    print(err)
```
Outputs:
```
error: Got 'THIRD' when expecting enum 'EKind' with one of values: FIRST, SECOND
in "[SomeClass] my_file.yml", line 1, column 1:
kind: THIRD
^ (line: 1)
```

If you desire to retrieve this information and print error yourself, access it's ``source`` field in error, or use injected methods ``get_root_source`` or ``get_field_source``.
```python
try:
    obj =  yaml_loader.load_yaml_dataclass(SomeClass, 'broken_file.yml', broken_yaml_content, always_track_source=True)
    field_src = obj.get_field_source('my_field_name')
    print(f"Value location line '{field_src.line_number}', column '{field_src.column_number}'")
except DataclassLoadError as err:
    print(f"Error location line '{err.source.line_number}', column '{err.source.column_number}'")
```

Additionaly, you can control how many lines are loaded for code snippet and in which format line numbers are presented via ``error_code_snippet_lines`` and ``error_format`` (Pretty or MSVC compatible).

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "bentoudev.dataclass",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "yaml,dataclass",
    "author": "BentouDev",
    "author_email": "",
    "download_url": "https://files.pythonhosted.org/packages/ec/d1/5394d2128c372db69e716929058c34858b49d0b05ed0ee3a947d6775cd76/bentoudev.dataclass-1.6.0.tar.gz",
    "platform": null,
    "description": "# Bentoudev.dataclass\n\n[![CI (on push)](https://github.com/BentouDev/Bentoudev.dataclass/actions/workflows/python-ci.yml/badge.svg)](https://github.com/BentouDev/Bentoudev.dataclass/actions/workflows/python-ci.yml) [![PyPI version](https://badge.fury.io/py/bentoudev.dataclass.svg)](https://badge.fury.io/py/bentoudev.dataclass)\n\nYaml to dataclass loader. Validates objects based on type information.\n\nSupports folowing types:\n- classes marked as dataclass (from ``dataclasses``)\n- int, str, float, list\n- Enum (from ``enum``)\n- Optional, List, Dict, Union (from ``typing``)\n- forward references to not yet known types (see example), including self-referencing\n\n## Install\n```sh\npip install bentoudev.dataclass\n```\n\n## Documentation\nWork in progress, for now, check out examples below or browse the source code.\n\n## Example\n\n```python\n@dataclass\nclass Person:\n    name: str\n    age: int\n    money: float\n\nyaml_content = (\n    'name: John\\n'\n    'age: 30\\n'\n    'money: 400.50'\n)\n\nobj = load_yaml_dataclass(Person, 'Person', yaml_content)\n\nassert obj.name == 'John'\n```\n\n### Inline loaders\nIf you need to load complex class from a single value (like string), you can use ``@inline_loader`` attribute\n\n```python\nimport bentoudev.dataclass.yaml_loader\nimport bentoudev.dataclass.base\n\n@dataclass\n@inline_loader(source_type=str, field_name='name')\nclass ObjFromStr:\n    name: str\n    foo: int\n    bar: float\n\n@dataclass\nclass Container:\n    value: ObjFromStr\n\nobj = load_yaml_dataclass(Container, 'pretty file name', 'value: ThisIsMyName')\n\nassert obj.value.name == 'ThisIsMyName'\n```\n### Forward references to external types\nSometimes you might want to load dataclass that forward references foreign types, from other modules, in form of a string. In order to support such types, loader must be supplied with list of them.\n```python\n\n@dataclass\nclass MyDataclass:\n    foo: Optional['my_namespace.project.model.my_ext_dataclass']\n\nlocal_types = base.get_types_from_modules([__name__, 'my_namespace.project.model.my_ext_dataclass'])\n\nmy_obj: MyDataclass = yaml_loader.load_yaml_dataclass(MyDataclass, 'pretty file name', yaml_content, ext_types=local_types)\n```\n\n### Self referencing types\nAdditionaly to external types, self referencing is also supported\n\n```python\nfrom dataclasses import dataclass\nimport bentoudev.dataclass.yaml_loader as yaml_loader\n\n@dataclass\nclass MyDataclass:\n    my_string: str\n    self_nested: Optional['MyDataclass']\n    list_of_sth: List[str]\n    user_data: Dict[str, str]\n\nyaml_content = (\n    'my_string: foo\\n'\n    'self_nested:\\n'\n    '  my_string: bar\\n'\n    '  list_of_sth: inline_value\\n'\n    'list_of_sth:\\n'\n    '- first\\n'\n    '- second\\n'\n    'user_data:\\n'\n    '  anything: goes'\n)\n\nmy_obj: MyDataclass = yaml_loader.load_yaml_dataclass(MyDataclass, 'pretty file name', yaml_content)\n```\n### Remember lines\nAdditional information about source from which obj/field was loaded can be enabled by using ``@track_source`` attribute, or setting ``always_track_source`` parameter to True (disabled by default, but recomended). Such information is then used to print prettier errors in ``DataclassLoadError``.\n\n```python\nclass EKind(Enum):\n    FIRST = 1\n    SECOND = 2\n\n@dataclass\nclass SomeClass:\n    kind: EKind\n\ntry:\n    obj =  yaml_loader.load_yaml_dataclass(SomeClass, '[SomeClass] my_file.yml', 'kind: THIRD', always_track_source=True)\nexcept DataclassLoadError as err:\n    print(err)\n```\nOutputs:\n```\nerror: Got 'THIRD' when expecting enum 'EKind' with one of values: FIRST, SECOND\nin \"[SomeClass] my_file.yml\", line 1, column 1:\nkind: THIRD\n^ (line: 1)\n```\n\nIf you desire to retrieve this information and print error yourself, access it's ``source`` field in error, or use injected methods ``get_root_source`` or ``get_field_source``.\n```python\ntry:\n    obj =  yaml_loader.load_yaml_dataclass(SomeClass, 'broken_file.yml', broken_yaml_content, always_track_source=True)\n    field_src = obj.get_field_source('my_field_name')\n    print(f\"Value location line '{field_src.line_number}', column '{field_src.column_number}'\")\nexcept DataclassLoadError as err:\n    print(f\"Error location line '{err.source.line_number}', column '{err.source.column_number}'\")\n```\n\nAdditionaly, you can control how many lines are loaded for code snippet and in which format line numbers are presented via ``error_code_snippet_lines`` and ``error_format`` (Pretty or MSVC compatible).\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "Yaml to dataclass loader",
    "version": "1.6.0",
    "project_urls": {
        "Homepage": "https://github.com/BentouDev/zetsubou.dataclass"
    },
    "split_keywords": [
        "yaml",
        "dataclass"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4068c4b40c97d63e61c805a752fdd2a53c4bbf05a8f6f2950a43a0626b21db35",
                "md5": "be56bbcea87269dd784810898d053ac8",
                "sha256": "d43029f5c3f7c34d44bf3ee3f8f23c4275688871115a77584f0c46cc9b8bb386"
            },
            "downloads": -1,
            "filename": "bentoudev.dataclass-1.6.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "be56bbcea87269dd784810898d053ac8",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 13481,
            "upload_time": "2024-02-15T21:43:34",
            "upload_time_iso_8601": "2024-02-15T21:43:34.198777Z",
            "url": "https://files.pythonhosted.org/packages/40/68/c4b40c97d63e61c805a752fdd2a53c4bbf05a8f6f2950a43a0626b21db35/bentoudev.dataclass-1.6.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ecd15394d2128c372db69e716929058c34858b49d0b05ed0ee3a947d6775cd76",
                "md5": "2850c29d8c5b8a5e68cbc834b5b4f568",
                "sha256": "60ea438f2c11e49f8cedf075bfbc8f85edb417b4a9d80cd87e8a0c2c85e4797c"
            },
            "downloads": -1,
            "filename": "bentoudev.dataclass-1.6.0.tar.gz",
            "has_sig": false,
            "md5_digest": "2850c29d8c5b8a5e68cbc834b5b4f568",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 17570,
            "upload_time": "2024-02-15T21:43:35",
            "upload_time_iso_8601": "2024-02-15T21:43:35.390736Z",
            "url": "https://files.pythonhosted.org/packages/ec/d1/5394d2128c372db69e716929058c34858b49d0b05ed0ee3a947d6775cd76/bentoudev.dataclass-1.6.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-15 21:43:35",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "BentouDev",
    "github_project": "zetsubou.dataclass",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "bentoudev.dataclass"
}
        
Elapsed time: 0.19244s