Skip to main content

simple library based on python +3.8 to use Dataclass-syntax for interacting with Data

Project description

DataModel

DataModel is a simple library based on python +3.8 to use Dataclass-syntax for interacting with Data, using the same syntax of Dataclass, users can write Python Objects and work with Data in the same way (like ORM's), is a reimplementation of python Dataclasses supporting true inheritance (without decorators), true composition and other good features.

The key features are:

  • Easy to use: No more using decorators, concerns abour re-ordering attributes or common problems with using dataclasses with inheritance.
  • Extensibility: Can use other dataclasses, Data objects or primitives as data-types.
  • Fast: DataModel is a replacement 100% full compatible with dataclasses, without any overhead.

Requirements

Python 3.8+

Installation

$ pip install python-datamodel
---> 100%
Successfully installed datamodel

Quickstart

from datamodel import Field, BaseModel
from dataclasses import dataclass, fields, is_dataclass


# This pure Dataclass:
@dataclass
class Point:
    x: int = Field(default=0, min=0, max=10)
    y: int = Field(default=0, min=0, max=10)

point = Point(x=10, y=10)
print(point)
print(fields(point))
print('IS a Dataclass?: ', is_dataclass(point))

# Can be represented by BaseModel
class newPoint(BaseModel):
    x: int = Field(default=0, min=0, max=10)
    y: int = Field(default=0, min=0, max=10)

    def get_coordinate(self):
        return (self.x, self.y)

point = newPoint(x=10, y=10)
print(point)
print(fields(point))
print('IS a Dataclass?: ', is_dataclass(point))
print(point.get_coordinate())

Supported types

DataModel support recursive transformation of fields, so you can easily work with nested dataclasses or complex types.

DataModel supports automatic conversion of:

  • datetime objects. datetime objects are encoded to str exactly like orjson conversion, any str typed as datetime is decoded to datetime. The same behavior is used to decoding time, date and timedelta objects.

  • UUID objects. They are encoded as str (JSON string) and decoded back to uuid.UUID objects.

  • Decimal objects. They are also encoded as float and decoded back to Decimal.

Also, "custom" encoders are supported.

import uuid
from typing import (
    List,
    Optional,
    Union
)
from dataclasses import dataclass, field
from datamodel import BaseModel, Field

@dataclass
class Point:
    x: int = Field(default=0, min=0, max=10)
    y: int = Field(default=0, min=0, max=10)

class coordinate(BaseModel, intSum):
    latitude: float
    longitude: float

    def get_location(self) -> tuple:
        return (self.latitude, self.longitude)

def auto_uid():
    return uuid.uuid4()

def default_rect():
    return [0,0,0,0]

def valid_zipcode(field, value):
    return value > 1000

class Address(BaseModel):
    id: uuid.UUID = field(default_factory=auto_uid)
    street: str = Field(required=True)
    zipcode: int = Field(required=False, default=1010, validator=valid_zipcode)
    location: Optional[coordinate]
    box: List[Optional[Point]]
    rect: List[int] = Field(factory=default_rect)


addr = Address(street="Calle Mayor", location=(18.1, 22.1), zipcode=3021, box=[(2, 10), (4, 8)], rect=[1, 2, 3, 4])
print('IS a Dataclass?: ', is_dataclass(addr))

print(addr.location.get_location())
# returns
Address(id=UUID('24b34dd5-8d35-4cfd-8916-7876b28cdae3'), street='Calle Mayor', zipcode=3021, location=coordinate(latitude=18.1, longitude=22.1), box=[Point(x=2, y=10), Point(x=4, y=8)], rect=[1, 2, 3, 4])
  • Fast and convenience conversion from-to JSON (using orjson):
import orjson

b = addr.json()
print(b)
{"id":"24b34dd5-8d35-4cfd-8916-7876b28cdae3","street":"Calle Mayor","zipcode":3021,"location":{"latitude":18.1,"longitude":22.1}, "box":[{"x":2,"y":10},{"x":4,"y":8}],"rect":[1,2,3,4]}
# and re-imported from json
new_addr = Address.from_json(b) # load directly from json string
# or using a dictionary decoded by orjson
data = orjson.loads(b)
new_addr = Address(**data)

Inheritance

python-datamodel supports inheritance of classes.

import uuid
from typing import Union, List
from dataclasses import dataclass, field
from datamodel import BaseModel, Column, Field


def auto_uid():
    return uuid.uuid4()

class User(BaseModel):
    id: uuid.UUID = field(default_factory=auto_uid)
    name: str
    first_name: str
    last_name: str


@dataclass
class Address:
    street: str
    city: str
    state: str
    zipcode: str
    country: Optional[str] = 'US'

    def __str__(self) -> str:
        """Provides pretty response of address"""
        lines = [self.street]
        lines.append(f"{self.city}, {self.zipcode} {self.state}")
        lines.append(f"{self.country}")
        return "\n".join(lines)

class Employee(User):
    """
    Base Employee.
    """
    role: str
    address: Address # composition of a dataclass inside of DataModel is possible.

# Supporting multiple inheritance and composition
# Wage Policies
class MonthlySalary(BaseModel):
    salary: Union[float, int]

    def calculate_payroll(self) -> Union[float, int]:
        return self.salary

class HourlySalary(BaseModel):
    salary: Union[float, int] = Field(default=0)
    hours_worked: Union[float, int] = Field(default=0)

    def calculate_payroll(self) -> Union[float, int]:
        return (self.hours_worked * self.salary)

# employee types
class Secretary(Employee, MonthlySalary):
    """Secretary.

    Person with montly salary policy and no commissions.
    """
    role: str = 'Secretary'

class FactoryWorker(Employee, HourlySalary):
    """
    FactoryWorker is an employee with hourly salary policy and no commissions.
    """
    role: str = 'Factory Worker'

class PayrollSystem:
    def calculate_payroll(self, employees: List[dataclass]) -> None:
        print('=== Calculating Payroll === ')
        for employee in employees:
            print(f"Payroll for employee {employee.id} - {employee.name}")
            print(f"- {employee.role} Amount: {employee.calculate_payroll()}")
            if employee.address:
                print('- Sent to:')
                print(employee.address)
            print("")

jane = Secretary(name='Jane Doe', first_name='Jane', last_name='Doe', salary=1500)
bob = FactoryWorker(name='Bob Doyle', first_name='Bob', last_name='Doyle', salary=15, hours_worked=40)
mitch = FactoryWorker(name='Mitch Brian', first_name='Mitch', last_name='Brian', salary=20, hours_worked=35)

payroll = PayrollSystem()
payroll.calculate_payroll([jane, bob, mitch])

A sample of output:

```console
=== Calculating Payroll ===
Payroll for employee 745a2623-d4d2-4da6-bf0a-1fa691bafd33 - Jane Doe
- Secretary Amount: 1500
- Sent to:
Rodeo Drive, Rd
Los Angeles, 31050 CA
US

Contributing

First of all, thank you for being interested in contributing to this library. I really appreciate you taking the time to work on this project.

  • If you're just interested in getting into the code, a good place to start are issues tagged as bugs.
  • If introducing a new feature, especially one that modifies the public API, consider submitting an issue for discussion before a PR. Please also take a look at existing issues / PRs to see what you're proposing has already been covered before / exists.
  • I like to follow the commit conventions documented here

License

This project is licensed under the terms of the BSD v3. license.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

python_datamodel-0.10.21.tar.gz (1.4 MB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

python_datamodel-0.10.21-cp313-cp313-win_amd64.whl (2.1 MB view details)

Uploaded CPython 3.13Windows x86-64

python_datamodel-0.10.21-cp313-cp313-win32.whl (2.1 MB view details)

Uploaded CPython 3.13Windows x86

python_datamodel-0.10.21-cp313-cp313-musllinux_1_2_x86_64.whl (5.7 MB view details)

Uploaded CPython 3.13musllinux: musl 1.2+ x86-64

python_datamodel-0.10.21-cp313-cp313-manylinux_2_28_x86_64.whl (5.7 MB view details)

Uploaded CPython 3.13manylinux: glibc 2.28+ x86-64

python_datamodel-0.10.21-cp312-cp312-win_amd64.whl (2.1 MB view details)

Uploaded CPython 3.12Windows x86-64

python_datamodel-0.10.21-cp312-cp312-win32.whl (2.1 MB view details)

Uploaded CPython 3.12Windows x86

python_datamodel-0.10.21-cp312-cp312-musllinux_1_2_x86_64.whl (5.8 MB view details)

Uploaded CPython 3.12musllinux: musl 1.2+ x86-64

python_datamodel-0.10.21-cp312-cp312-manylinux_2_28_x86_64.whl (5.8 MB view details)

Uploaded CPython 3.12manylinux: glibc 2.28+ x86-64

python_datamodel-0.10.21-cp311-cp311-win_amd64.whl (2.1 MB view details)

Uploaded CPython 3.11Windows x86-64

python_datamodel-0.10.21-cp311-cp311-win32.whl (2.1 MB view details)

Uploaded CPython 3.11Windows x86

python_datamodel-0.10.21-cp311-cp311-musllinux_1_2_x86_64.whl (5.8 MB view details)

Uploaded CPython 3.11musllinux: musl 1.2+ x86-64

python_datamodel-0.10.21-cp311-cp311-manylinux_2_28_x86_64.whl (5.8 MB view details)

Uploaded CPython 3.11manylinux: glibc 2.28+ x86-64

python_datamodel-0.10.21-cp310-cp310-win_amd64.whl (2.1 MB view details)

Uploaded CPython 3.10Windows x86-64

python_datamodel-0.10.21-cp310-cp310-win32.whl (2.1 MB view details)

Uploaded CPython 3.10Windows x86

python_datamodel-0.10.21-cp310-cp310-musllinux_1_2_x86_64.whl (5.4 MB view details)

Uploaded CPython 3.10musllinux: musl 1.2+ x86-64

python_datamodel-0.10.21-cp310-cp310-manylinux_2_28_x86_64.whl (5.4 MB view details)

Uploaded CPython 3.10manylinux: glibc 2.28+ x86-64

File details

Details for the file python_datamodel-0.10.21.tar.gz.

File metadata

  • Download URL: python_datamodel-0.10.21.tar.gz
  • Upload date:
  • Size: 1.4 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for python_datamodel-0.10.21.tar.gz
Algorithm Hash digest
SHA256 47276ebeda4beccc66bc87678c2792edb85e93afbd6560954a36a1a21430b3d1
MD5 17ae8628fc3c9c7373e5b0bf6f52d3dc
BLAKE2b-256 6caf18ce9d72a7b560e99783c8d588541589aa7b4de027b66ab47733cec07938

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp313-cp313-win_amd64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 0eeb820b7b1247caf873a2d8efbf7ea5be5cbaaebee0079d8acc671c0db6ea37
MD5 239a99a37be8e8aad1f6b75220bac30d
BLAKE2b-256 c64f2fcecdd95f3806c68ddc494c1daf53ff6f2def3da554f7ea9af6b9822cae

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp313-cp313-win32.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp313-cp313-win32.whl
Algorithm Hash digest
SHA256 8b4516d3ba1bc56d42772276753012f82c4f345c036bdf5bd10f853f43c2a280
MD5 bb165203bc0c804af9b3fbe92313eca4
BLAKE2b-256 b5cbd8d8902e5a34a940c519aea265952aafa21c48a56cbe8f36ed9fbbb583d0

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp313-cp313-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp313-cp313-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 fc57675aad6ec47813d0468dfd7fed2392c3f03ef116eaae075c81de002973e7
MD5 5ef385e9914b005da4905108ddbb7c96
BLAKE2b-256 58f250d1bd32fbd0b01b928b1862b1b2a5e1af72c3c1ca49ba5c8d7d447a70a5

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp313-cp313-manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp313-cp313-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 8ba0cc32dc2ec0a538e8d5afe7dd9ff677d3abdb5e2d4da578ef71d1dbf42347
MD5 a8cd3d4b6a2b204f92ad34ec21c790bc
BLAKE2b-256 f75223d8d8d2611b18612c81c3cf4210038594561548946f35e95220e22b749e

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp312-cp312-win_amd64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 3df8a917395da21da864e34df95f1e472cdbce82ebf3599fc0183002cd3909fe
MD5 f621e53dcf2d664f2e15afe5ff68318c
BLAKE2b-256 14669b573cec770371a0faaa5206832444b0ece6cc54890e37242fcb9c5aed69

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp312-cp312-win32.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp312-cp312-win32.whl
Algorithm Hash digest
SHA256 7d069e9c5fcc4db3549ca863f9166430af2f3e0dcd0679aad13ea9b389eda15f
MD5 633c7213cfe9317302843a9f36353d0f
BLAKE2b-256 06b815129263c99cf749ea461b5853001b4a2c8208912b7cef21218a9162e524

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp312-cp312-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp312-cp312-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 6f3c09045ac09a92248c4466840860985f55d9554fa0e5e081fd455845ee0fb5
MD5 4e012f54a64ca3ce6aa3ecb36c34b62a
BLAKE2b-256 180951302e3626b70f9386f42acd2e4c137acc20f67d24b57424323c4f379f0e

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp312-cp312-manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp312-cp312-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 50e6b1c21ae0f19949de8d8094ff18c16c7d6369a99c0a2011dd9eb0d7c590ad
MD5 7477e96ecc434d9d04d2696c76e2eec2
BLAKE2b-256 16545de39e4ae4de0751817a3c999d47e9f2614fec1d97d9133b66091f4258de

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp311-cp311-win_amd64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 7b83d8c7e390c4559439068bda93799aff5272bb23f4d3741eb8e53cdb20c6cd
MD5 0c34a3b9226a6e059ea7ccade2a9e68e
BLAKE2b-256 ff4680ee4be67d3a7a212416e94049cca18607ae87ff3fe4a5237391db16ab23

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp311-cp311-win32.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp311-cp311-win32.whl
Algorithm Hash digest
SHA256 cd2e0773adf523614304caca6c7329b6a19db7323796602c239d615132be05ac
MD5 e2226b97556821f6779796e8fd8e7ead
BLAKE2b-256 5fe35f0e49b728b0498839174d9542ae63426f6d6e597e1508e0a9ed07317ca0

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp311-cp311-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp311-cp311-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 4a62e1fab2e4ad17812f07600a15d417dceea31b69174f7ceb2c5f1b607712f5
MD5 0a3545a55f953123e36fac7bc6bb8082
BLAKE2b-256 5c94d233e4cab9910b2f1c2aa5a4e23ac63537c67a471aab2079fd2ce7c7ccfd

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp311-cp311-manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp311-cp311-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 24f5f163df4f31609082cf7b627c4f887a9a5c57f00c3e1e42b3fd741b7b7f6b
MD5 751f09bda7c23a2de04c994591228f3e
BLAKE2b-256 c2342eb8da0e568878a55d1a2d8251e3fd2dcb6e011f6a55da7dc5b339595759

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp310-cp310-win_amd64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 73e12ba213a7a8a746011b8cda8a37ab8788159af337905725fb8c198325585e
MD5 1e38900d464958a61c6544da071eab7b
BLAKE2b-256 1876295710dbe6f08e3c584dc71abe3d5e10e60fe949570c7024b88a8d9df02a

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp310-cp310-win32.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp310-cp310-win32.whl
Algorithm Hash digest
SHA256 f5b24306bcbb3d5ef15fe4bedcca2a7264cddb28539d9c12681585a3e036edc8
MD5 d1294fddbdf17aa07ba59ca2bf6935fc
BLAKE2b-256 d663e7f78b6649bbe6f3ac3a107f5d8af74c6e1ff83637c0e64f83fc0257cb30

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp310-cp310-musllinux_1_2_x86_64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp310-cp310-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 40cf35117b8855dc42fc7ffb758227ec9389f1962b155ee347ebc302cf945042
MD5 bd7b401a63cfc6ea93dfda503bc2ff52
BLAKE2b-256 a64075b1c12be33ff22b3f11380273d8595e288679eb2894a98d0b9a292602e7

See more details on using hashes here.

File details

Details for the file python_datamodel-0.10.21-cp310-cp310-manylinux_2_28_x86_64.whl.

File metadata

File hashes

Hashes for python_datamodel-0.10.21-cp310-cp310-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 c01ba9463d0d9771a36ba21984377a35d94db48ead77bd4002188d5ae29b5d6f
MD5 a59a9865c15d9d8d54f08c2b6e399c27
BLAKE2b-256 2952c12b4a985d2ada0eb8b94dca74a800997c973fd9ddac36d7c10667a8b8b7

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page