datclass


Namedatclass JSON
Version 0.2.28 PyPI version JSON
download
home_pageNone
Summarypython package dataclass utils
upload_time2024-10-08 03:47:49
maintainerNone
docs_urlNone
authorfoyoux
requires_python>=3.7
licenseNone
keywords dataclass dataclasses utils nested extra attrs json
VCS
bugtrack_url
requirements typing_extensions
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # datclass

python dataclass nested & extra attrs

Extending the official [dataclass](https://docs.python.org/zh-cn/3/library/dataclasses.html) to support nested and extended fields.

## Install

[![PyPI](https://img.shields.io/pypi/v/datclass)](https://pypi.org/project/datclass/) [![python version](https://img.shields.io/pypi/pyversions/datclass)](https://pypi.org/project/datclass/)  [![Downloads](https://static.pepy.tech/personalized-badge/datclass?period=total&units=international_system&left_color=black&right_color=orange&left_text=Downloads)](https://pepy.tech/project/datclass)

```sh
pip install -U datclass
pip install git+ssh://git@github.com/foyoux/datclass.git
pip install git+https://github.com/foyoux/datclass.git
```

## Usage example

### Example 1

```py
from dataclasses import dataclass
from typing import List

# Default `dataclass` supports nested and extended fields. Missing fields will be logged.
from datclass import DatClass


# Custom `DatClass`
# from datclass import get_datclass
# Missing fields will not be logged.
# DatClass = get_datclass(log=False)


@dataclass
class User(DatClass):
    name: str
    age: int


@dataclass
class Group(DatClass):
    name: str
    users: List[User]


if __name__ == '__main__':
    user1 = User(name='foo', age=18)
    # Saving a data class to a file.
    user1.to_file('user.json')
    # Adding some control parameters.
    user1.to_file('user.json', indent=4, ignore_none=True, sort_keys=True)

    # Creating a data class from a dict.
    user2 = User(**{'name': 'bar', 'age': 20})
    # To convert a data class to a dictionary, you can support extended fields.
    # You can also use the official asdict function, but it cannot export extended fields.
    dict1 = user2.to_dict()
    # 'ignore_none' is used to ignore values that are None.
    dict2 = user2.to_dict(ignore_none=True)

    # Creating a data class from a string.
    user3 = User.from_str('{"name": "baz", "age": 22}')
    # Convert the data class to a JSON string.
    dict3 = user3.to_str()
    dict4 = user3.to_str(indent=4, ignore_none=True)

    # Creating a data class from a file.
    user4 = User.from_file('user.json')

    # Nested data classes
    grp = Group(name='group1', users=[user1, user2, user3, user4])
    grp.to_file('group.json', indent=4, ignore_none=True, sort_keys=True)

    for user in grp.users:
        print(user.name, user.age)

    # Extending fields
    user = {'name': 'foo', 'age': 18, 'sex': 1}
    user5 = User(**user)
    assert user5.to_dict() == user

```

### Example 2

```py
from dataclasses import dataclass
from typing import ClassVar, Dict

from datclass import DatClass


@dataclass
class User(DatClass):
    name: str
    age: int
    attr_123: str

    # Renaming fields.
    __rename_attrs__: ClassVar[Dict[str, str]] = {
        'Name': 'name',
        'Age': 'age',
        '123#$^%^%*': 'attr_123'
    }

    # This way of writing is also acceptable.
    # __rename_attrs__ = {
    #     'Name': 'name',
    #     'Age': 'age',
    #     '123#$^%^%*': 'attr_123',
    # }


if __name__ == '__main__':
    s = '{"Name": "foo", "Age": 18, "123#$^%^%*": "test rename attrs"}'
    user = User.from_str(s)
    assert user.to_str() == s

```

## Automatically generate `DataClass`

See the `datclass` command for details.

```sh
$ datclass -h

```

### Example 1

Input `user.json`

```json
{
  "Name": "foo",
  "Age": 18,
  "123#$^%^%*": "test rename attrs"
}
```

Execute the command

```sh
$ datclass -o user.py user.json

```

Output user.py

```py
from dataclasses import dataclass

from datclass import DatClass


@dataclass
class Object(DatClass):
    a_123: str = None  # rename from '123#$^%^%*'
    age: int = None  # rename from 'Age'
    name: str = None  # rename from 'Name'

    __rename_attrs__ = {
        'Name': 'name',
        'Age': 'age',
        '123#$^%^%*': 'a_123',
    }

```

---

欢迎反馈和建议

Feedback and suggestions welcome

https://github.com/foyoux/datclass/issues/new

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "datclass",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "dataclass, dataclasses, utils, nested, extra, attrs, json",
    "author": "foyoux",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/43/b6/52392616582cf1497ef2589f674911122d75de8f2ef4a04e52583d2e113c/datclass-0.2.28.tar.gz",
    "platform": null,
    "description": "# datclass\n\npython dataclass nested & extra attrs\n\nExtending the official [dataclass](https://docs.python.org/zh-cn/3/library/dataclasses.html) to support nested and extended fields.\n\n## Install\n\n[![PyPI](https://img.shields.io/pypi/v/datclass)](https://pypi.org/project/datclass/) [![python version](https://img.shields.io/pypi/pyversions/datclass)](https://pypi.org/project/datclass/)  [![Downloads](https://static.pepy.tech/personalized-badge/datclass?period=total&units=international_system&left_color=black&right_color=orange&left_text=Downloads)](https://pepy.tech/project/datclass)\n\n```sh\npip install -U datclass\npip install git+ssh://git@github.com/foyoux/datclass.git\npip install git+https://github.com/foyoux/datclass.git\n```\n\n## Usage example\n\n### Example 1\n\n```py\nfrom dataclasses import dataclass\nfrom typing import List\n\n# Default `dataclass` supports nested and extended fields. Missing fields will be logged.\nfrom datclass import DatClass\n\n\n# Custom `DatClass`\n# from datclass import get_datclass\n# Missing fields will not be logged.\n# DatClass = get_datclass(log=False)\n\n\n@dataclass\nclass User(DatClass):\n    name: str\n    age: int\n\n\n@dataclass\nclass Group(DatClass):\n    name: str\n    users: List[User]\n\n\nif __name__ == '__main__':\n    user1 = User(name='foo', age=18)\n    # Saving a data class to a file.\n    user1.to_file('user.json')\n    # Adding some control parameters.\n    user1.to_file('user.json', indent=4, ignore_none=True, sort_keys=True)\n\n    # Creating a data class from a dict.\n    user2 = User(**{'name': 'bar', 'age': 20})\n    # To convert a data class to a dictionary, you can support extended fields.\n    # You can also use the official asdict function, but it cannot export extended fields.\n    dict1 = user2.to_dict()\n    # 'ignore_none' is used to ignore values that are None.\n    dict2 = user2.to_dict(ignore_none=True)\n\n    # Creating a data class from a string.\n    user3 = User.from_str('{\"name\": \"baz\", \"age\": 22}')\n    # Convert the data class to a JSON string.\n    dict3 = user3.to_str()\n    dict4 = user3.to_str(indent=4, ignore_none=True)\n\n    # Creating a data class from a file.\n    user4 = User.from_file('user.json')\n\n    # Nested data classes\n    grp = Group(name='group1', users=[user1, user2, user3, user4])\n    grp.to_file('group.json', indent=4, ignore_none=True, sort_keys=True)\n\n    for user in grp.users:\n        print(user.name, user.age)\n\n    # Extending fields\n    user = {'name': 'foo', 'age': 18, 'sex': 1}\n    user5 = User(**user)\n    assert user5.to_dict() == user\n\n```\n\n### Example 2\n\n```py\nfrom dataclasses import dataclass\nfrom typing import ClassVar, Dict\n\nfrom datclass import DatClass\n\n\n@dataclass\nclass User(DatClass):\n    name: str\n    age: int\n    attr_123: str\n\n    # Renaming fields.\n    __rename_attrs__: ClassVar[Dict[str, str]] = {\n        'Name': 'name',\n        'Age': 'age',\n        '123#$^%^%*': 'attr_123'\n    }\n\n    # This way of writing is also acceptable.\n    # __rename_attrs__ = {\n    #     'Name': 'name',\n    #     'Age': 'age',\n    #     '123#$^%^%*': 'attr_123',\n    # }\n\n\nif __name__ == '__main__':\n    s = '{\"Name\": \"foo\", \"Age\": 18, \"123#$^%^%*\": \"test rename attrs\"}'\n    user = User.from_str(s)\n    assert user.to_str() == s\n\n```\n\n## Automatically generate `DataClass`\n\nSee the `datclass` command for details.\n\n```sh\n$ datclass -h\n\n```\n\n### Example 1\n\nInput `user.json`\n\n```json\n{\n  \"Name\": \"foo\",\n  \"Age\": 18,\n  \"123#$^%^%*\": \"test rename attrs\"\n}\n```\n\nExecute the command\n\n```sh\n$ datclass -o user.py user.json\n\n```\n\nOutput user.py\n\n```py\nfrom dataclasses import dataclass\n\nfrom datclass import DatClass\n\n\n@dataclass\nclass Object(DatClass):\n    a_123: str = None  # rename from '123#$^%^%*'\n    age: int = None  # rename from 'Age'\n    name: str = None  # rename from 'Name'\n\n    __rename_attrs__ = {\n        'Name': 'name',\n        'Age': 'age',\n        '123#$^%^%*': 'a_123',\n    }\n\n```\n\n---\n\n\u6b22\u8fce\u53cd\u9988\u548c\u5efa\u8bae\n\nFeedback and suggestions welcome\n\nhttps://github.com/foyoux/datclass/issues/new\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "python package dataclass utils",
    "version": "0.2.28",
    "project_urls": {
        "Bug Tracker": "https://github.com/foyoux/datclass/issues",
        "Homepage": "https://github.com/foyoux/datclass",
        "Source": "https://github.com/foyoux/datclass"
    },
    "split_keywords": [
        "dataclass",
        " dataclasses",
        " utils",
        " nested",
        " extra",
        " attrs",
        " json"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4332feac5c9ceda0fa544bfe9341498d73e4d664a91b78c3e27a855f26aa6687",
                "md5": "4902a0b162d078e9f26bd1d4cae5bca4",
                "sha256": "3ff2aa3d20e599a98664a496d978ffa105d3c0765cf02ad13d0e5e2c266ae538"
            },
            "downloads": -1,
            "filename": "datclass-0.2.28-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "4902a0b162d078e9f26bd1d4cae5bca4",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 12606,
            "upload_time": "2024-10-08T03:47:47",
            "upload_time_iso_8601": "2024-10-08T03:47:47.986926Z",
            "url": "https://files.pythonhosted.org/packages/43/32/feac5c9ceda0fa544bfe9341498d73e4d664a91b78c3e27a855f26aa6687/datclass-0.2.28-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "43b652392616582cf1497ef2589f674911122d75de8f2ef4a04e52583d2e113c",
                "md5": "663daeffe28ca5003d11c52f68a50761",
                "sha256": "1c5643f8caea3439127b1e53c686516e75e814485461e7174ff1f698483082ad"
            },
            "downloads": -1,
            "filename": "datclass-0.2.28.tar.gz",
            "has_sig": false,
            "md5_digest": "663daeffe28ca5003d11c52f68a50761",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 13015,
            "upload_time": "2024-10-08T03:47:49",
            "upload_time_iso_8601": "2024-10-08T03:47:49.277191Z",
            "url": "https://files.pythonhosted.org/packages/43/b6/52392616582cf1497ef2589f674911122d75de8f2ef4a04e52583d2e113c/datclass-0.2.28.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-08 03:47:49",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "foyoux",
    "github_project": "datclass",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "typing_extensions",
            "specs": []
        }
    ],
    "lcname": "datclass"
}
        
Elapsed time: 0.36178s