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.20.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.20-cp313-cp313-win_amd64.whl (2.1 MB view details)

Uploaded CPython 3.13Windows x86-64

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

Uploaded CPython 3.13Windows x86

python_datamodel-0.10.20-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.20-cp313-cp313-manylinux_2_28_x86_64.whl (5.8 MB view details)

Uploaded CPython 3.13manylinux: glibc 2.28+ x86-64

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

Uploaded CPython 3.12Windows x86-64

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

Uploaded CPython 3.12Windows x86

python_datamodel-0.10.20-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.20-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.20-cp311-cp311-win_amd64.whl (2.2 MB view details)

Uploaded CPython 3.11Windows x86-64

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

Uploaded CPython 3.11Windows x86

python_datamodel-0.10.20-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.20-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.20-cp310-cp310-win_amd64.whl (2.1 MB view details)

Uploaded CPython 3.10Windows x86-64

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

Uploaded CPython 3.10Windows x86

python_datamodel-0.10.20-cp310-cp310-musllinux_1_2_x86_64.whl (5.5 MB view details)

Uploaded CPython 3.10musllinux: musl 1.2+ x86-64

python_datamodel-0.10.20-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.20.tar.gz.

File metadata

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

File hashes

Hashes for python_datamodel-0.10.20.tar.gz
Algorithm Hash digest
SHA256 11c7f6795c840ec563aa652c9a10eb36822f2570ec0754f463f41929c1535091
MD5 08c896ff813cd0064bcbe802f173296f
BLAKE2b-256 a2b1ededfb24713b245319e5f184d0aec0df2705a8dad2e7da5a5899ab661252

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp313-cp313-win_amd64.whl
Algorithm Hash digest
SHA256 4f63dbaa2007f57b6e113d0a0dd9ffb37d27b9859c6c56576047ac89e667e5c7
MD5 c93501fec4636b2fa55b961bbc0320ae
BLAKE2b-256 b804d688dd0b3a965131ca4defbb0ea66a6da2b6c53a27ccf4cdeaaa271bc408

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp313-cp313-win32.whl
Algorithm Hash digest
SHA256 7deef2180edb38c33e6a93ae763346d95d8dba0142dde8fb1d3a0ab74fe8ee6e
MD5 a61c04568a7330e6b0b46c7d28f19b62
BLAKE2b-256 dc6830fbfc85b3636fd4b9eeee2042fe0fda38b49877e3f7b9ff8d2e086e4a2c

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp313-cp313-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 40e09f493ffe0a8df61a2e8f2ef584f2a8db3e3808ea6c74977fcb1758e0cf8e
MD5 ca2953e2c67f4c026c3abf9914ffb6bf
BLAKE2b-256 c8dd2cf2daba7492a2657321eae709d768014f27bb1ac5cf58d28975b98ebae1

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp313-cp313-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 dc4ca61b77813f920f72e74f80de24d877f88ef6d720568257d91f40331ea071
MD5 6355ac0f81947e350290564be65be9e3
BLAKE2b-256 4e35f3b55fc28412c31f77a904404fb14cda1ada7c00d1b538df70e2768f0d3c

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 27bca7519b910bc46c72d6188df5ecef44bcbfa56a3e115a12d59242640ee12a
MD5 e2fde4e4f4e6fadc3685877e76ba6d74
BLAKE2b-256 9b6e2d0824eef300af49576f92d1fbd0180f8ba432f29ba1a584981b60be29b8

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp312-cp312-win32.whl
Algorithm Hash digest
SHA256 3516724dd66377e366641c168eb44069bd4e41a0f084096968dc7055ecb20d70
MD5 02395e81fc99a3992a279abb3e3c3284
BLAKE2b-256 8f82a92ddb64bb17650baaa15fe92e5248c29d6c99ae0d96c915ac97ce9cde86

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp312-cp312-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 e4e6d66542576f17e12409e4e945a838690a075efc403ab7704cdbd4407ecee6
MD5 88a6825da779756b6dd3359b8ca7c73a
BLAKE2b-256 14650dc7170100e4c71cfb41c8dd308cc0fb93924a5319bb7b3436b15603e3c6

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp312-cp312-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 823a87a403201fafa93de6e069a99b8ae51be6fc68377bc3e14aceb869c9b675
MD5 2854f8c6e2f8be45cba2acfd023361b5
BLAKE2b-256 1765997143f089b94356b058f1613f48a23f04c81f83ee60da9b6375094fe799

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp311-cp311-win_amd64.whl
Algorithm Hash digest
SHA256 880fb5ccbaf8187d3f5ddaafd5633b798f12dd56b177e7b7742fd6b6796055e5
MD5 6d9c11b89762f7e4ee9a3d677321d2b8
BLAKE2b-256 23095a1634f28bff8283b72d0b53f2da283abcffb6efa3d606ad83c7df8bf533

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp311-cp311-win32.whl
Algorithm Hash digest
SHA256 698bd27119f95f24d06ced52f6ae0bdc8ddf9af3eb291c8bdad5221f69611e69
MD5 9f54dd36a6714418f1e909620add8a49
BLAKE2b-256 de1f6359597cf2fa5159a51602f7181f3c71cd0a5d432837292ec742df829450

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp311-cp311-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 092df9af1c4b873095ff4bee6b05235a0da17774db948ee57ccb8d034e15dce7
MD5 958a770b50c4c4ecbc639c3b76bca453
BLAKE2b-256 28e27749e3005092451f225ee06f2c6dfa408b04e6f67c1af619c59b00450309

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp311-cp311-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 f296a1ce349947ac5e36e7e29496525859c8c7031ea805f54cf99f5183e85ea8
MD5 56ec6359c4d7432c2e359bb3b1b987e5
BLAKE2b-256 ba76ea3dffe66cebcd1bf5d4aead365a95fcde3f482f2a2684c544e7463e35ff

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp310-cp310-win_amd64.whl
Algorithm Hash digest
SHA256 97223d03fa89f7355fedc6ccbcc7a66571c4c070c95a78d835b9badb5fce07d4
MD5 89a04838a5db7efbf95c3f6226ad3848
BLAKE2b-256 05164aa58488cefb969c4eaff294953d178022661eafde2f62fb37e11e373f43

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp310-cp310-win32.whl
Algorithm Hash digest
SHA256 54901c0f252d6f76a0be8879e8ae2ec59f0f7191fcdd7d91c6f0a6aa5609d65c
MD5 8cce812871dcca6a30724af9e2275f55
BLAKE2b-256 ef3b6282d40b50a95e54ad81f8ae8a9fb36e087d8c7b797a36e61d0beeaf54ec

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp310-cp310-musllinux_1_2_x86_64.whl
Algorithm Hash digest
SHA256 3bf756297355af09d9cd17b1e05c5fdc1c0ea79f02d0273b33c5a4459e02fed8
MD5 e5b218cb10f2ebc6558848f208780f92
BLAKE2b-256 bdfb9a509d66e4d1828db89baa10880c3559b32703c1c369e9183b5aea81b178

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for python_datamodel-0.10.20-cp310-cp310-manylinux_2_28_x86_64.whl
Algorithm Hash digest
SHA256 159ef5b55cea9781b55182fde5488906260c5ea59edf2947132ce29b0f940db6
MD5 cd92c3dcab7dc974108472016d3a3d77
BLAKE2b-256 83082226d8f671a661c7e4042efc26e68c2c04aae4525c458daf99a07038437e

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