Warning: You are using the test version of PyPI. This is a pre-production deployment of Warehouse. Changes made here affect the production instance of TestPyPI (testpypi.python.org).
Help us improve Python packaging - Donate today!

Parsing mixin which converts ``data class instance``, ``dict object``, ``json string`` and ``yaml string`` each other.

Project Description

Parsing mixin which converts data class instance, dict object, json string and yaml string each other.

Motivation

Have you ever wanted to write robust code in Python? This library will make such your wishes come true.

Define your data class which is extend DictMixin, you can use some useful methods which help your codes robust. See following Example and API sections.

Example

You don’t need to use typing necessarily, but I recommend to use this to make your codes more robust. See PEP 484 – Type Hints.

from typing import Text, Optional
from dictmixin import DictMixin

class Food(DictMixin):
    def __init__(self, id, name, color=None):
        self.id = id  # type: Text
        self.name = name  # type: Text
        self.color = color  # type: Optional[Text]

class Human(DictMixin):
    def __init__(self, id, name, favorite):
        self.id = id  # type: Text
        self.name = name  # type: Text
        self.favorite = Food.from_dict2list(favorite)  # type: Food

jiro = Human.from_dict({
    "id": 10,
    "name": "jiro",
    "favorite": [
        {"id": 1, "name": "apple"},
        {"id": 2, "name": "orange", "color": "white"}
    ]
})

>>> jiro.id
10
>>> jiro.name
'jiro'
>>> print(jiro.favorite[0].to_pretty_json())
{
    "color": null,
    "id": 1,
    "name": "apple"
}
>>> print(jiro.to_dict())
{'favorite': [{'color': None, 'id': 1, 'name': 'apple'}, {'color': 'white', 'id': 2, 'name': 'orange'}], 'id': 10, 'name': 'jiro'}

API

From instance to another

  • to_dict
    • instance => dict
  • to_json
    • instance => json string
  • to_pretty_json
    • instance => json string (has indent and line break)
  • to_yaml
    • instance => yaml string

From something to instance

  • from_dict
    • dict => instance [1]
  • from_dict2list
    • dict => List[instance] [1]
  • from_dict2dict
    • dict => Dict[instance] [1]
  • from_json
    • json string => instance
  • from_yaml
    • yaml string => instance
[1](1, 2, 3) Also includes optional methods. (from_optional_xxx)

Installation

pip install dictmixin
Release History

Release History

This version
History Node

0.5.1

Supported By

WebFaction WebFaction Technical Writing Elastic Elastic Search Pingdom Pingdom Monitoring Dyn Dyn DNS Sentry Sentry Error Logging CloudAMQP CloudAMQP RabbitMQ Heroku Heroku PaaS Kabu Creative Kabu Creative UX & Design Fastly Fastly CDN DigiCert DigiCert EV Certificate Rackspace Rackspace Cloud Servers DreamHost DreamHost Log Hosting