dacite2


Namedacite2 JSON
Version 2.0.0 PyPI version JSON
download
home_pagehttps://github.com/idanmiara/dacite
SummarySimple creation of data classes from dictionaries (fork of dacite).
upload_time2022-12-05 10:26:03
maintainerIdan Miara
docs_urlNone
authorKonrad Hałas
requires_python>=3.7
licenseMIT
keywords dataclasses
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage No coveralls.
            # dacite2

[![Build Status](https://travis-ci.org/idanmiara/dacite.svg?branch=master)](https://travis-ci.org/idanmiara/dacite)
[![Coverage Status](https://coveralls.io/repos/github/idanmiara/dacite/badge.svg?branch=master)](https://coveralls.io/github/idanmiara/dacite?branch=master)
[![License](https://img.shields.io/pypi/l/dacite.svg)](https://pypi.python.org/pypi/dacite/)
[![Version](https://img.shields.io/pypi/v/dacite.svg)](https://pypi.python.org/pypi/dacite/)
[![Python versions](https://img.shields.io/pypi/pyversions/dacite.svg)](https://pypi.python.org/pypi/dacite/)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black)

This is a fork of `dacite`: https://github.com/konradhalas/dacite

This module simplifies creation of data classes ([PEP 557][pep-557])
from dictionaries.

## Installation

To install dacite, simply use `pip`:

```
$ pip install dacite2
```

## Requirements

Minimum Python version supported by `dacite2` is 3.7.

## Quick start

```python
from dataclasses import dataclass
from dacite import from_dict


@dataclass
class User:
    name: str
    age: int
    is_active: bool


data = {
    'name': 'John',
    'age': 30,
    'is_active': True,
}

user = from_dict(data_class=User, data=data)

assert user == User(name='John', age=30, is_active=True)
```

## Features

Dacite supports following features:

- nested structures
- (basic) types checking
- optional fields (i.e. `typing.Optional`)
- unions
- forward references
- collections
- custom type hooks

## Motivation

Passing plain dictionaries as a data container between your functions or
methods isn't a good practice. Of course you can always create your
custom class instead, but this solution is an overkill if you only want
to merge a few fields within a single object.

Fortunately Python has a good solution to this problem - data classes.
Thanks to `@dataclass` decorator you can easily create a new custom
type with a list of given fields in a declarative manner. Data classes
support type hints by design.

However, even if you are using data classes, you have to create their
instances somehow. In many such cases, your input is a dictionary - it
can be a payload from a HTTP request or a raw data from a database. If
you want to convert those dictionaries into data classes, `dacite` is
your best friend.

This library was originally created to simplify creation of type hinted
data transfer objects (DTO) which can cross the boundaries in the
application architecture.

It's important to mention that `dacite` is not a data validation library.
There are dozens of awesome data validation projects and it doesn't make
sense to duplicate this functionality within `dacite`. If you want to 
validate your data first, you should combine `dacite` with one of data 
validation library.

Please check [Use Case](#use-case) section for a real-life example.

## Usage

Dacite is based on a single function - `dacite.from_dict`. This function
takes 3 parameters:

- `data_class` - data class type
- `data` - dictionary of input data
- `config` (optional) - configuration of the creation process, instance
of `dacite.Config` class

Configuration is a (data) class with following fields:

- `type_hooks`
- `cast`
- `forward_references`
- `check_types`
- `strict`
- `strict_unions_match`

The examples below show all features of `from_dict` function and usage
of all `Config` parameters.

### Nested structures

You can pass a data with nested dictionaries and it will create a proper
result.

```python
@dataclass
class A:
    x: str
    y: int


@dataclass
class B:
    a: A


data = {
    'a': {
        'x': 'test',
        'y': 1,
    }
}

result = from_dict(data_class=B, data=data)

assert result == B(a=A(x='test', y=1))
```

### Optional fields

Whenever your data class has a `Optional` field and you will not provide
input data for this field, it will take the `None` value.

```python
from typing import Optional

@dataclass
class A:
    x: str
    y: Optional[int]


data = {
    'x': 'test',
}

result = from_dict(data_class=A, data=data)

assert result == A(x='test', y=None)
```

### Unions

If your field can accept multiple types, you should use `Union`. Dacite
will try to match data with provided types one by one. If none will
match, it will raise `UnionMatchError` exception.

```python
from typing import Union

@dataclass
class A:
    x: str

@dataclass
class B:
    y: int

@dataclass
class C:
    u: Union[A, B]


data = {
    'u': {
        'y': 1,
    },
}

result = from_dict(data_class=C, data=data)

assert result == C(u=B(y=1))
```

### Collections

Dacite supports fields defined as collections. It works for both - basic
types and data classes.

```python
@dataclass
class A:
    x: str
    y: int


@dataclass
class B:
    a_list: List[A]


data = {
    'a_list': [
        {
            'x': 'test1',
            'y': 1,
        },
        {
            'x': 'test2',
            'y': 2,
        }
    ],
}

result = from_dict(data_class=B, data=data)

assert result == B(a_list=[A(x='test1', y=1), A(x='test2', y=2)])
```

### Type hooks

You can use `Config.type_hooks` argument if you want to transform the input 
data of a data class field with given type into the new value. You have to 
pass a mapping of type `Mapping[Type, Callable[[Any], Any]`.

```python
@dataclass
class A:
    x: str


data = {
    'x': 'TEST',
}

result = from_dict(data_class=A, data=data, config=Config(type_hooks={str: str.lower}))

assert result == A(x='test')
```

If a data class field type is a `Optional[T]` you can pass both - 
`Optional[T]` or just `T` - as a key in `type_hooks`. The same with generic 
collections, e.g. when a field has type `List[T]` you can use `List[T]` to 
transform whole collection or `T` to transform each item. 

To target all types use `Any`.  Targeting collections without their sub-types
will target all collections of those types, such as `List` and `Dict`. 

```python
@dataclass
class ShoppingCart:
    store: str
    item_ids: List[int]

data = {
    'store': '7-Eleven',
    'item_ids': [1, 2, 3],
}

def print_value(value):
    print(value)
    return value

def print_collection(collection):
    for item in collection:
        print(item)
    return collection

result = from_dict(
    data_class=ShoppingCart, 
    data=data, 
    config=Config(
        type_hooks={
            Any: print_value, 
            List: print_collection
        }
    )
)
```

prints

```
7-Eleven
[1, 2, 3]
1
2
3
```

If a data class field type is a `Optional[T]` you can pass both - 
`Optional[T]` or just `T` - as a key in `type_hooks`. The same with generic 
collections, e.g. when a field has type `List[T]` you can use `List[T]` to 
transform whole collection or `T` to transform each item. 

### Casting

It's a very common case that you want to create an instance of a field type 
from the input data with just calling your type with the input value. Of 
course you can use `type_hooks={T: T}` to achieve this goal but `cast=[T]` is 
an easier and more expressive way. It also works with base classes - if `T` 
is a base class of type `S`, all fields of type `S` will be also "casted".

```python
from enum import Enum

class E(Enum):
    X = 'x'
    Y = 'y'
    Z = 'z'

@dataclass
class A:
    e: E


data = {
    'e': 'x',
}

result = from_dict(data_class=A, data=data, config=Config(cast=[E]))

# or

result = from_dict(data_class=A, data=data, config=Config(cast=[Enum]))

assert result == A(e=E.X)
```

### Forward References

Definition of forward references can be passed as a `{'name': Type}` mapping to 
`Config.forward_references`. This dict is passed to `typing.get_type_hints()` as the 
`globalns` param when evaluating each field's type.

```python
@dataclass
class X:
    y: "Y"

@dataclass
class Y:
    s: str

data = from_dict(X, {"y": {"s": "text"}}, Config(forward_references={"Y": Y}))
assert data == X(Y("text"))
```

### Types checking

There are rare cases when `dacite` built-in type checker can not validate 
your types (e.g. custom generic class) or you have such functionality 
covered by other library and you don't want to validate your types twice. 
In such case you can disable type checking with `Config(check_types=False)`.
By default types checking is enabled.

```python
T = TypeVar('T')


class X(Generic[T]):
    pass


@dataclass
class A:
    x: X[str]


x = X[str]()

assert from_dict(A, {'x': x}, config=Config(check_types=False)) == A(x=x)
```

### Strict mode

By default `from_dict` ignores additional keys (not matching data class field) 
in the input data. If you want change this behaviour set `Config.strict` to 
`True`. In case of unexpected key `from_dict` will raise `UnexpectedDataError` 
exception.

### Strict unions match

`Union` allows to define multiple possible types for a given field. By default 
`dacite` is trying to find the first matching type for a provided data and it 
returns instance of this type. It means that it's possible that there are other 
matching types further on the `Union` types list. With `strict_unions_match` 
only a single match is allowed, otherwise `dacite` raises `StrictUnionMatchError`.

## Exceptions

Whenever something goes wrong, `from_dict` will raise adequate
exception. There are a few of them:

- `WrongTypeError` - raised when a type of a input value does not match
with a type of a data class field
- `MissingValueError` - raised when you don't provide a value for a
required field
- `UnionMatchError` - raised when provided data does not match any type
of `Union`
- `ForwardReferenceError` - raised when undefined forward reference encountered in
dataclass
- `UnexpectedDataError` - raised when `strict` mode is enabled and the input 
data has not matching keys
- `StrictUnionMatchError` - raised when `strict_unions_match` mode is enabled 
and the input data has ambiguous `Union` match

## Development

First of all - if you want to submit your pull request, thank you very much! 
I really appreciate your support.

Please remember that every new feature, bug fix or improvement should be tested. 
100% code coverage is a must have. 

We are using a few static code analysis tools to increase the code quality 
(`black`, `mypy`, `pylint`). Please make sure that you are not generating any 
errors/warnings before you submit your PR. You can find current configuration
in `.travis.yml` file.

Last but not least, if you want to introduce new feature, please discuss it 
first within an issue.

### How to start

Clone `dacite` repository:

```
$ git clone git@github.com:idanmiara/dacite.git
```

Create and activate virtualenv in the way you like:

```
$ python3 -m venv dacite-env
$ source dacite-env/bin/activate
```

Install all `dacite` dependencies:

```
$ pip install -e .[dev]
```

To run tests you just have to fire:

```
$ pytest
```
 
 
## Use case

There are many cases when we receive "raw" data (Python dicts) as a input to 
our system. HTTP request payload is a very common use case. In most web 
frameworks we receive request data as a simple dictionary. Instead of 
passing this dict down to your "business" code, it's a good idea to create 
something more "robust".

Following example is a simple `flask` app - it has single `/products` endpoint.
You can use this endpoint to "create" product in your system. Our core 
`create_product` function expects data class as a parameter. Thanks to `dacite` 
we can easily build such data class from `POST` request payload.


```python
from dataclasses import dataclass
from typing import List

from flask import Flask, request, Response

import dacite

app = Flask(__name__)


@dataclass
class ProductVariantData:
    code: str
    description: str = ''
    stock: int = 0


@dataclass
class ProductData:
    name: str
    price: float
    variants: List[ProductVariantData]


def create_product(product_data: ProductData) -> None:
    pass  # your business logic here


@app.route("/products", methods=['POST'])
def products():
    product_data = dacite.from_dict(
        data_class=ProductData,
        data=request.get_json(),
    )
    create_product(product_data=product_data)
    return Response(status=201)

```

What if we want to validate our data (e.g. check if `code` has 6 characters)? 
Such features are out of scope of `dacite` but we can easily combine it with 
one of data validation library. Let's try with 
[marshmallow](https://marshmallow.readthedocs.io).

First of all we have to define our data validation schemas:

```python
from marshmallow import Schema, fields, ValidationError


def validate_code(code):
    if len(code) != 6:
        raise ValidationError('Code must have 6 characters.')


class ProductVariantDataSchema(Schema):
    code = fields.Str(required=True, validate=validate_code)
    description = fields.Str(required=False)
    stock = fields.Int(required=False)


class ProductDataSchema(Schema):
    name = fields.Str(required=True)
    price = fields.Decimal(required=True)
    variants = fields.Nested(ProductVariantDataSchema(many=True))
```

And use them within our endpoint:

```python
@app.route("/products", methods=['POST'])
def products():
    schema = ProductDataSchema()
    result, errors = schema.load(request.get_json())
    if errors:
        return Response(
            response=json.dumps(errors), 
            status=400, 
            mimetype='application/json',
        )
    product_data = dacite.from_dict(
        data_class=ProductData,
        data=result,
    )
    create_product(product_data=product_data)
    return Response(status=201)
```

Still `dacite` helps us to create data class from "raw" dict with validated data.

## Changelog

Follow `dacite` updates in [CHANGELOG][changelog].

## Authors

Created by [Konrad Hałas][halas-homepage].
Maintained by [Idan Miara][miara-email].

[pep-557]: https://www.python.org/dev/peps/pep-0557/
[halas-homepage]: https://konradhalas.pl
[miara-email]: idan@miara.com
[changelog]: https://github.com/idanmiara/dacite/blob/master/CHANGELOG.md

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/idanmiara/dacite",
    "name": "dacite2",
    "maintainer": "Idan Miara",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "idan@miara.com",
    "keywords": "dataclasses",
    "author": "Konrad Ha\u0142as",
    "author_email": "halas.konrad@gmail.com",
    "download_url": "",
    "platform": null,
    "description": "# dacite2\r\n\r\n[![Build Status](https://travis-ci.org/idanmiara/dacite.svg?branch=master)](https://travis-ci.org/idanmiara/dacite)\r\n[![Coverage Status](https://coveralls.io/repos/github/idanmiara/dacite/badge.svg?branch=master)](https://coveralls.io/github/idanmiara/dacite?branch=master)\r\n[![License](https://img.shields.io/pypi/l/dacite.svg)](https://pypi.python.org/pypi/dacite/)\r\n[![Version](https://img.shields.io/pypi/v/dacite.svg)](https://pypi.python.org/pypi/dacite/)\r\n[![Python versions](https://img.shields.io/pypi/pyversions/dacite.svg)](https://pypi.python.org/pypi/dacite/)\r\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/ambv/black)\r\n\r\nThis is a fork of `dacite`: https://github.com/konradhalas/dacite\r\n\r\nThis module simplifies creation of data classes ([PEP 557][pep-557])\r\nfrom dictionaries.\r\n\r\n## Installation\r\n\r\nTo install dacite, simply use `pip`:\r\n\r\n```\r\n$ pip install dacite2\r\n```\r\n\r\n## Requirements\r\n\r\nMinimum Python version supported by `dacite2` is 3.7.\r\n\r\n## Quick start\r\n\r\n```python\r\nfrom dataclasses import dataclass\r\nfrom dacite import from_dict\r\n\r\n\r\n@dataclass\r\nclass User:\r\n    name: str\r\n    age: int\r\n    is_active: bool\r\n\r\n\r\ndata = {\r\n    'name': 'John',\r\n    'age': 30,\r\n    'is_active': True,\r\n}\r\n\r\nuser = from_dict(data_class=User, data=data)\r\n\r\nassert user == User(name='John', age=30, is_active=True)\r\n```\r\n\r\n## Features\r\n\r\nDacite supports following features:\r\n\r\n- nested structures\r\n- (basic) types checking\r\n- optional fields (i.e. `typing.Optional`)\r\n- unions\r\n- forward references\r\n- collections\r\n- custom type hooks\r\n\r\n## Motivation\r\n\r\nPassing plain dictionaries as a data container between your functions or\r\nmethods isn't a good practice. Of course you can always create your\r\ncustom class instead, but this solution is an overkill if you only want\r\nto merge a few fields within a single object.\r\n\r\nFortunately Python has a good solution to this problem - data classes.\r\nThanks to `@dataclass` decorator you can easily create a new custom\r\ntype with a list of given fields in a declarative manner. Data classes\r\nsupport type hints by design.\r\n\r\nHowever, even if you are using data classes, you have to create their\r\ninstances somehow. In many such cases, your input is a dictionary - it\r\ncan be a payload from a HTTP request or a raw data from a database. If\r\nyou want to convert those dictionaries into data classes, `dacite` is\r\nyour best friend.\r\n\r\nThis library was originally created to simplify creation of type hinted\r\ndata transfer objects (DTO) which can cross the boundaries in the\r\napplication architecture.\r\n\r\nIt's important to mention that `dacite` is not a data validation library.\r\nThere are dozens of awesome data validation projects and it doesn't make\r\nsense to duplicate this functionality within `dacite`. If you want to \r\nvalidate your data first, you should combine `dacite` with one of data \r\nvalidation library.\r\n\r\nPlease check [Use Case](#use-case) section for a real-life example.\r\n\r\n## Usage\r\n\r\nDacite is based on a single function - `dacite.from_dict`. This function\r\ntakes 3 parameters:\r\n\r\n- `data_class` - data class type\r\n- `data` - dictionary of input data\r\n- `config` (optional) - configuration of the creation process, instance\r\nof `dacite.Config` class\r\n\r\nConfiguration is a (data) class with following fields:\r\n\r\n- `type_hooks`\r\n- `cast`\r\n- `forward_references`\r\n- `check_types`\r\n- `strict`\r\n- `strict_unions_match`\r\n\r\nThe examples below show all features of `from_dict` function and usage\r\nof all `Config` parameters.\r\n\r\n### Nested structures\r\n\r\nYou can pass a data with nested dictionaries and it will create a proper\r\nresult.\r\n\r\n```python\r\n@dataclass\r\nclass A:\r\n    x: str\r\n    y: int\r\n\r\n\r\n@dataclass\r\nclass B:\r\n    a: A\r\n\r\n\r\ndata = {\r\n    'a': {\r\n        'x': 'test',\r\n        'y': 1,\r\n    }\r\n}\r\n\r\nresult = from_dict(data_class=B, data=data)\r\n\r\nassert result == B(a=A(x='test', y=1))\r\n```\r\n\r\n### Optional fields\r\n\r\nWhenever your data class has a `Optional` field and you will not provide\r\ninput data for this field, it will take the `None` value.\r\n\r\n```python\r\nfrom typing import Optional\r\n\r\n@dataclass\r\nclass A:\r\n    x: str\r\n    y: Optional[int]\r\n\r\n\r\ndata = {\r\n    'x': 'test',\r\n}\r\n\r\nresult = from_dict(data_class=A, data=data)\r\n\r\nassert result == A(x='test', y=None)\r\n```\r\n\r\n### Unions\r\n\r\nIf your field can accept multiple types, you should use `Union`. Dacite\r\nwill try to match data with provided types one by one. If none will\r\nmatch, it will raise `UnionMatchError` exception.\r\n\r\n```python\r\nfrom typing import Union\r\n\r\n@dataclass\r\nclass A:\r\n    x: str\r\n\r\n@dataclass\r\nclass B:\r\n    y: int\r\n\r\n@dataclass\r\nclass C:\r\n    u: Union[A, B]\r\n\r\n\r\ndata = {\r\n    'u': {\r\n        'y': 1,\r\n    },\r\n}\r\n\r\nresult = from_dict(data_class=C, data=data)\r\n\r\nassert result == C(u=B(y=1))\r\n```\r\n\r\n### Collections\r\n\r\nDacite supports fields defined as collections. It works for both - basic\r\ntypes and data classes.\r\n\r\n```python\r\n@dataclass\r\nclass A:\r\n    x: str\r\n    y: int\r\n\r\n\r\n@dataclass\r\nclass B:\r\n    a_list: List[A]\r\n\r\n\r\ndata = {\r\n    'a_list': [\r\n        {\r\n            'x': 'test1',\r\n            'y': 1,\r\n        },\r\n        {\r\n            'x': 'test2',\r\n            'y': 2,\r\n        }\r\n    ],\r\n}\r\n\r\nresult = from_dict(data_class=B, data=data)\r\n\r\nassert result == B(a_list=[A(x='test1', y=1), A(x='test2', y=2)])\r\n```\r\n\r\n### Type hooks\r\n\r\nYou can use `Config.type_hooks` argument if you want to transform the input \r\ndata of a data class field with given type into the new value. You have to \r\npass a mapping of type `Mapping[Type, Callable[[Any], Any]`.\r\n\r\n```python\r\n@dataclass\r\nclass A:\r\n    x: str\r\n\r\n\r\ndata = {\r\n    'x': 'TEST',\r\n}\r\n\r\nresult = from_dict(data_class=A, data=data, config=Config(type_hooks={str: str.lower}))\r\n\r\nassert result == A(x='test')\r\n```\r\n\r\nIf a data class field type is a `Optional[T]` you can pass both - \r\n`Optional[T]` or just `T` - as a key in `type_hooks`. The same with generic \r\ncollections, e.g. when a field has type `List[T]` you can use `List[T]` to \r\ntransform whole collection or `T` to transform each item. \r\n\r\nTo target all types use `Any`.  Targeting collections without their sub-types\r\nwill target all collections of those types, such as `List` and `Dict`. \r\n\r\n```python\r\n@dataclass\r\nclass ShoppingCart:\r\n    store: str\r\n    item_ids: List[int]\r\n\r\ndata = {\r\n    'store': '7-Eleven',\r\n    'item_ids': [1, 2, 3],\r\n}\r\n\r\ndef print_value(value):\r\n    print(value)\r\n    return value\r\n\r\ndef print_collection(collection):\r\n    for item in collection:\r\n        print(item)\r\n    return collection\r\n\r\nresult = from_dict(\r\n    data_class=ShoppingCart, \r\n    data=data, \r\n    config=Config(\r\n        type_hooks={\r\n            Any: print_value, \r\n            List: print_collection\r\n        }\r\n    )\r\n)\r\n```\r\n\r\nprints\r\n\r\n```\r\n7-Eleven\r\n[1, 2, 3]\r\n1\r\n2\r\n3\r\n```\r\n\r\nIf a data class field type is a `Optional[T]` you can pass both - \r\n`Optional[T]` or just `T` - as a key in `type_hooks`. The same with generic \r\ncollections, e.g. when a field has type `List[T]` you can use `List[T]` to \r\ntransform whole collection or `T` to transform each item. \r\n\r\n### Casting\r\n\r\nIt's a very common case that you want to create an instance of a field type \r\nfrom the input data with just calling your type with the input value. Of \r\ncourse you can use `type_hooks={T: T}` to achieve this goal but `cast=[T]` is \r\nan easier and more expressive way. It also works with base classes - if `T` \r\nis a base class of type `S`, all fields of type `S` will be also \"casted\".\r\n\r\n```python\r\nfrom enum import Enum\r\n\r\nclass E(Enum):\r\n    X = 'x'\r\n    Y = 'y'\r\n    Z = 'z'\r\n\r\n@dataclass\r\nclass A:\r\n    e: E\r\n\r\n\r\ndata = {\r\n    'e': 'x',\r\n}\r\n\r\nresult = from_dict(data_class=A, data=data, config=Config(cast=[E]))\r\n\r\n# or\r\n\r\nresult = from_dict(data_class=A, data=data, config=Config(cast=[Enum]))\r\n\r\nassert result == A(e=E.X)\r\n```\r\n\r\n### Forward References\r\n\r\nDefinition of forward references can be passed as a `{'name': Type}` mapping to \r\n`Config.forward_references`. This dict is passed to `typing.get_type_hints()` as the \r\n`globalns` param when evaluating each field's type.\r\n\r\n```python\r\n@dataclass\r\nclass X:\r\n    y: \"Y\"\r\n\r\n@dataclass\r\nclass Y:\r\n    s: str\r\n\r\ndata = from_dict(X, {\"y\": {\"s\": \"text\"}}, Config(forward_references={\"Y\": Y}))\r\nassert data == X(Y(\"text\"))\r\n```\r\n\r\n### Types checking\r\n\r\nThere are rare cases when `dacite` built-in type checker can not validate \r\nyour types (e.g. custom generic class) or you have such functionality \r\ncovered by other library and you don't want to validate your types twice. \r\nIn such case you can disable type checking with `Config(check_types=False)`.\r\nBy default types checking is enabled.\r\n\r\n```python\r\nT = TypeVar('T')\r\n\r\n\r\nclass X(Generic[T]):\r\n    pass\r\n\r\n\r\n@dataclass\r\nclass A:\r\n    x: X[str]\r\n\r\n\r\nx = X[str]()\r\n\r\nassert from_dict(A, {'x': x}, config=Config(check_types=False)) == A(x=x)\r\n```\r\n\r\n### Strict mode\r\n\r\nBy default `from_dict` ignores additional keys (not matching data class field) \r\nin the input data. If you want change this behaviour set `Config.strict` to \r\n`True`. In case of unexpected key `from_dict` will raise `UnexpectedDataError` \r\nexception.\r\n\r\n### Strict unions match\r\n\r\n`Union` allows to define multiple possible types for a given field. By default \r\n`dacite` is trying to find the first matching type for a provided data and it \r\nreturns instance of this type. It means that it's possible that there are other \r\nmatching types further on the `Union` types list. With `strict_unions_match` \r\nonly a single match is allowed, otherwise `dacite` raises `StrictUnionMatchError`.\r\n\r\n## Exceptions\r\n\r\nWhenever something goes wrong, `from_dict` will raise adequate\r\nexception. There are a few of them:\r\n\r\n- `WrongTypeError` - raised when a type of a input value does not match\r\nwith a type of a data class field\r\n- `MissingValueError` - raised when you don't provide a value for a\r\nrequired field\r\n- `UnionMatchError` - raised when provided data does not match any type\r\nof `Union`\r\n- `ForwardReferenceError` - raised when undefined forward reference encountered in\r\ndataclass\r\n- `UnexpectedDataError` - raised when `strict` mode is enabled and the input \r\ndata has not matching keys\r\n- `StrictUnionMatchError` - raised when `strict_unions_match` mode is enabled \r\nand the input data has ambiguous `Union` match\r\n\r\n## Development\r\n\r\nFirst of all - if you want to submit your pull request, thank you very much! \r\nI really appreciate your support.\r\n\r\nPlease remember that every new feature, bug fix or improvement should be tested. \r\n100% code coverage is a must have. \r\n\r\nWe are using a few static code analysis tools to increase the code quality \r\n(`black`, `mypy`, `pylint`). Please make sure that you are not generating any \r\nerrors/warnings before you submit your PR. You can find current configuration\r\nin `.travis.yml` file.\r\n\r\nLast but not least, if you want to introduce new feature, please discuss it \r\nfirst within an issue.\r\n\r\n### How to start\r\n\r\nClone `dacite` repository:\r\n\r\n```\r\n$ git clone git@github.com:idanmiara/dacite.git\r\n```\r\n\r\nCreate and activate virtualenv in the way you like:\r\n\r\n```\r\n$ python3 -m venv dacite-env\r\n$ source dacite-env/bin/activate\r\n```\r\n\r\nInstall all `dacite` dependencies:\r\n\r\n```\r\n$ pip install -e .[dev]\r\n```\r\n\r\nTo run tests you just have to fire:\r\n\r\n```\r\n$ pytest\r\n```\r\n \r\n \r\n## Use case\r\n\r\nThere are many cases when we receive \"raw\" data (Python dicts) as a input to \r\nour system. HTTP request payload is a very common use case. In most web \r\nframeworks we receive request data as a simple dictionary. Instead of \r\npassing this dict down to your \"business\" code, it's a good idea to create \r\nsomething more \"robust\".\r\n\r\nFollowing example is a simple `flask` app - it has single `/products` endpoint.\r\nYou can use this endpoint to \"create\" product in your system. Our core \r\n`create_product` function expects data class as a parameter. Thanks to `dacite` \r\nwe can easily build such data class from `POST` request payload.\r\n\r\n\r\n```python\r\nfrom dataclasses import dataclass\r\nfrom typing import List\r\n\r\nfrom flask import Flask, request, Response\r\n\r\nimport dacite\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@dataclass\r\nclass ProductVariantData:\r\n    code: str\r\n    description: str = ''\r\n    stock: int = 0\r\n\r\n\r\n@dataclass\r\nclass ProductData:\r\n    name: str\r\n    price: float\r\n    variants: List[ProductVariantData]\r\n\r\n\r\ndef create_product(product_data: ProductData) -> None:\r\n    pass  # your business logic here\r\n\r\n\r\n@app.route(\"/products\", methods=['POST'])\r\ndef products():\r\n    product_data = dacite.from_dict(\r\n        data_class=ProductData,\r\n        data=request.get_json(),\r\n    )\r\n    create_product(product_data=product_data)\r\n    return Response(status=201)\r\n\r\n```\r\n\r\nWhat if we want to validate our data (e.g. check if `code` has 6 characters)? \r\nSuch features are out of scope of `dacite` but we can easily combine it with \r\none of data validation library. Let's try with \r\n[marshmallow](https://marshmallow.readthedocs.io).\r\n\r\nFirst of all we have to define our data validation schemas:\r\n\r\n```python\r\nfrom marshmallow import Schema, fields, ValidationError\r\n\r\n\r\ndef validate_code(code):\r\n    if len(code) != 6:\r\n        raise ValidationError('Code must have 6 characters.')\r\n\r\n\r\nclass ProductVariantDataSchema(Schema):\r\n    code = fields.Str(required=True, validate=validate_code)\r\n    description = fields.Str(required=False)\r\n    stock = fields.Int(required=False)\r\n\r\n\r\nclass ProductDataSchema(Schema):\r\n    name = fields.Str(required=True)\r\n    price = fields.Decimal(required=True)\r\n    variants = fields.Nested(ProductVariantDataSchema(many=True))\r\n```\r\n\r\nAnd use them within our endpoint:\r\n\r\n```python\r\n@app.route(\"/products\", methods=['POST'])\r\ndef products():\r\n    schema = ProductDataSchema()\r\n    result, errors = schema.load(request.get_json())\r\n    if errors:\r\n        return Response(\r\n            response=json.dumps(errors), \r\n            status=400, \r\n            mimetype='application/json',\r\n        )\r\n    product_data = dacite.from_dict(\r\n        data_class=ProductData,\r\n        data=result,\r\n    )\r\n    create_product(product_data=product_data)\r\n    return Response(status=201)\r\n```\r\n\r\nStill `dacite` helps us to create data class from \"raw\" dict with validated data.\r\n\r\n## Changelog\r\n\r\nFollow `dacite` updates in [CHANGELOG][changelog].\r\n\r\n## Authors\r\n\r\nCreated by [Konrad Ha\u0142as][halas-homepage].\r\nMaintained by [Idan Miara][miara-email].\r\n\r\n[pep-557]: https://www.python.org/dev/peps/pep-0557/\r\n[halas-homepage]: https://konradhalas.pl\r\n[miara-email]: idan@miara.com\r\n[changelog]: https://github.com/idanmiara/dacite/blob/master/CHANGELOG.md\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Simple creation of data classes from dictionaries (fork of dacite).",
    "version": "2.0.0",
    "split_keywords": [
        "dataclasses"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "410b18a7884d02080457a92504673c24",
                "sha256": "bf254194ca579871c58d8f0bd9b56f422bb302cb26af466da0e12c190e19f9c2"
            },
            "downloads": -1,
            "filename": "dacite2-2.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "410b18a7884d02080457a92504673c24",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 13885,
            "upload_time": "2022-12-05T10:26:03",
            "upload_time_iso_8601": "2022-12-05T10:26:03.727913Z",
            "url": "https://files.pythonhosted.org/packages/86/7a/8984c8641a95501cca7882b7affd1509b48ff9f0e4224575ded5fec984b7/dacite2-2.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2022-12-05 10:26:03",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "idanmiara",
    "github_project": "dacite",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": true,
    "lcname": "dacite2"
}
        
Elapsed time: 0.01972s