Collections of pydantic models

Overview

pydantic-collections

Build Status Coverage Status

The pydantic-collections package provides BaseCollectionModel class that allows you to manipulate collections of pydantic models (and any other types supported by pydantic).

Requirements

  • Python >= 3.7
  • pydantic >= 1.8.2

Installation

pip install pydantic-collections

Usage

Basic usage

from datetime import datetime

from pydantic import BaseModel
from pydantic_collections import BaseCollectionModel


class User(BaseModel):
    id: int
    name: str
    birth_date: datetime


class UserCollection(BaseCollectionModel[User]):
    pass


 user_data = [
        {'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'},
        {'id': 2, 'name': 'Balaganov', 'birth_date': '2020-04-01T12:59:59'},
    ]

users = UserCollection(user_data)
print(users)
#> UserCollection([User(id=1, name='Bender', birth_date=datetime.datetime(2010, 4, 1, 12, 59, 59)), User(id=2, name='Balaganov', birth_date=datetime.datetime(2020, 4, 1, 12, 59, 59))])
print(users.dict())
#> [{'id': 1, 'name': 'Bender', 'birth_date': datetime.datetime(2010, 4, 1, 12, 59, 59)}, {'id': 2, 'name': 'Balaganov', 'birth_date': datetime.datetime(2020, 4, 1, 12, 59, 59)}]
print(users.json())
#> [{"id": 1, "name": "Bender", "birth_date": "2010-04-01T12:59:59"}, {"id": 2, "name": "Balaganov", "birth_date": "2020-04-01T12:59:59"}]

Strict assignment validation

By default BaseCollectionModel has a strict assignment check

...
users = UserCollection()
users.append(User(id=1, name='Bender', birth_date=datetime.utcnow()))  # OK
users.append({'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'})
#> pydantic.error_wrappers.ValidationError: 1 validation error for UserCollection
#> __root__ -> 2
#>  instance of User expected (type=type_error.arbitrary_type; expected_arbitrary_type=User)

This behavior can be changed via Model Config

...
class UserCollection(BaseCollectionModel[User]):
    class Config:
        validate_assignment_strict = False
        
users = UserCollection()
users.append({'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'})  # OK
assert users[0].__class__ is User
assert users[0].id == 1

Using as a model field

BaseCollectionModel is a subclass of BaseModel, so you can use it as a model field

...
class UserContainer(BaseModel):
    users: UserCollection = []
        
data = {
    'users': [
        {'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'},
        {'id': 2, 'name': 'Balaganov', 'birth_date': '2020-04-01T12:59:59'},
    ]
}

container = UserContainer(**data)
container.users.append(User(...))
...
You might also like...
vartests is a Python library to perform some statistic tests to evaluate Value at Risk (VaR) Models

vartests is a Python library to perform some statistic tests to evaluate Value at Risk (VaR) Models, such as: T-test: verify if mean of distribution i

A model checker for verifying properties in epistemic models

Epistemic Model Checker This is a model checker for verifying properties in epistemic models. The goal of the model checker is to check for Pluralisti

Fit models to your data in Python with Sherpa.

Table of Contents Sherpa License How To Install Sherpa Using Anaconda Using pip Building from source History Release History Sherpa Sherpa is a modeli

 pydantic-i18n is an extension to support an i18n for the pydantic error messages.
pydantic-i18n is an extension to support an i18n for the pydantic error messages.

pydantic-i18n is an extension to support an i18n for the pydantic error messages

Python collections that are backended by sqlite3 DB and are compatible with the built-in collections

sqlitecollections Python collections that are backended by sqlite3 DB and are compatible with the built-in collections Installation $ pip install git+

Seamlessly integrate pydantic models in your Sphinx documentation.
Seamlessly integrate pydantic models in your Sphinx documentation.

Seamlessly integrate pydantic models in your Sphinx documentation.

🪄 Auto-generate Streamlit UI from Pydantic Models and Dataclasses.
🪄 Auto-generate Streamlit UI from Pydantic Models and Dataclasses.

Streamlit Pydantic Auto-generate Streamlit UI elements from Pydantic models. Getting Started • Documentation • Support • Report a Bug • Contribution •

Hyperlinks for pydantic models

Hyperlinks for pydantic models In a typical web application relationships between resources are modeled by primary and foreign keys in a database (int

Pydantic models for pywttr and aiopywttr.

Pydantic models for pywttr and aiopywttr.

EMNLP 2021 Adapting Language Models for Zero-shot Learning by Meta-tuning on Dataset and Prompt Collections

Adapting Language Models for Zero-shot Learning by Meta-tuning on Dataset and Prompt Collections Ruiqi Zhong, Kristy Lee*, Zheng Zhang*, Dan Klein EMN

PyTorch implementation of
PyTorch implementation of "Representing Shape Collections with Alignment-Aware Linear Models" paper.

deep-linear-shapes PyTorch implementation of "Representing Shape Collections with Alignment-Aware Linear Models" paper. If you find this code useful i

flask extension for integration with the awesome pydantic package

Flask-Pydantic Flask extension for integration of the awesome pydantic package with Flask. Installation python3 -m pip install Flask-Pydantic Basics v

flask extension for integration with the awesome pydantic package

Flask-Pydantic Flask extension for integration of the awesome pydantic package with Flask. Installation python3 -m pip install Flask-Pydantic Basics v

A curated list of awesome things related to Pydantic! 🌪️

Awesome Pydantic A curated list of awesome things related to Pydantic. These packages have not been vetted or approved by the pydantic team. Feel free

Pydantic model support for Django ORM

Pydantic model support for Django ORM

flask extension for integration with the awesome pydantic package

flask extension for integration with the awesome pydantic package

Flask Sugar is a web framework for building APIs with Flask, Pydantic and Python 3.6+ type hints.
Flask Sugar is a web framework for building APIs with Flask, Pydantic and Python 3.6+ type hints.

Flask Sugar is a web framework for building APIs with Flask, Pydantic and Python 3.6+ type hints. check parameters and generate API documents automatically. Flask Sugar是一个基于flask,pyddantic,类型注解的API框架, 可以检查参数并自动生成API文档

Pydantic-ish YAML configuration management.
Pydantic-ish YAML configuration management.

Pydantic-ish YAML configuration management.

(A)sync client for sms.ru with pydantic responses

🚧 aioSMSru Send SMS Check SMS status Get SMS cost Get balance Get limit Get free limit Get my senders Check login/password Add to stoplist Remove fro

Comments
  • Bug dict() method: ignore or raised exception when using dict function attribute (ex. include, exclude, etc.)

    Bug dict() method: ignore or raised exception when using dict function attribute (ex. include, exclude, etc.)

    Hi there, I tried to use the method dict but i got an error: KeyError(__root__) Here an example:

    1. Model structure:
    
    from datetime import datetime, time
    from typing import Optional, Union
    from pydantic import Field, validator, BaseModel
    from pydantic_collections import BaseCollectionModel
    
    class OpeningTime(BaseModel):
        weekday: int = Field(..., alias="weekday")
        day: Optional[str] = Field(alias="day")  # NB: keep it after number_weekday attribute
        from_time: Optional[time] = Field(alias="fromTime")
        to_time: Optional[time] = Field(alias="toTime")
    
        @validator("day", pre=True)
        def generate_weekday(cls, weekday: str, values) -> str:
            if weekday is None or len(weekday) == 0:
                return WEEKDAYS[str(values["weekday"])]
            return weekday
    
    
    
    class OpeningTimes(BaseCollectionModel[OpeningTime]):
        pass
    
    
    class PaymentMethod(BaseModel):
        type: str = Field(..., alias="type")
        card_type: str = Field(..., alias="cardType")
    
    
    class PaymentMethods(BaseCollectionModel[PaymentMethod]):
        pass
    
    
    class FuelType(BaseModel):
        type: str = Field(..., alias="Fuel")
    
    
    class FuelTypes(BaseCollectionModel[FuelType]):
        pass
    
    
    class AdditionalInfoStation(BaseModel):
        opening_times: Optional[OpeningTimes] = Field(alias="openingTimes")
        car_wash_opening_times: Optional[OpeningTimes] = Field(alias="openingTimesCarWash")
        payment_methods: PaymentMethods = Field(..., alias="paymentMethods")
        fuel_types: FuelTypes = Field(..., alias="fuelTypes")
    
    
    class Example(BaseModel):
        hash_key: int = Field(..., alias="hashKey")
        range_key: str = Field(..., alias="rangeKey")
        location_id: str = Field(..., alias="locationId")
        name: str = Field(..., alias="name")
        street: str = Field(..., alias="street")
        address_number: str = Field(..., alias="addressNumber")
        zip_code: int = Field(..., alias="zipCode")
        city: str = Field(..., alias="city")
        region: str = Field(..., alias="region")
        country: str = Field(..., alias="country")
        additional_info: Union[AdditionalInfoStation] = Field(..., alias="additionalInfo")
    
    
    class ExampleList(BaseCollectionModel[EniGeoPoint]):
        pass
    
    1. Imagine that there is an ExampleList populated object and needed filters field during apply of dict method:
    example_list: ExampleList = ExampleList.parse_obj([{......}])
    
    #This istruction raised exception
    example_list.dict(by_alias=True, inlcude={"hash_key", "range_key"})
    
    1. The last istruction raise an error: Message: KeyError('__root__')

    My env is:

    • pydantic==1.9.1
    • pydantic-collections==0.2.0
    • python version 3.9.7

    If you need more info please contact me.

    opened by aferrari94 6
Releases(v0.4.0)
Owner
Roman Snegirev
Roman Snegirev
Bigdata Simulation Library Of Dream By Sandman Books

BIGDATA SIMULATION LIBRARY OF DREAM BY SANDMAN BOOKS ================= Solution Architecture Description In the realm of Dreaming, its ruler SANDMAN,

Maycon Cypriano 3 Jun 30, 2022
Port of dplyr and other related R packages in python, using pipda.

Unlike other similar packages in python that just mimic the piping syntax, datar follows the API designs from the original packages as much as possible, and is tested thoroughly with the cases from t

179 Dec 21, 2022
This is a python script to navigate and extract the FSD50K dataset

FSD50K navigator This is a script I use to navigate the sound dataset from FSK50K.

sweemeng 2 Nov 23, 2021
A Python package for modular causal inference analysis and model evaluations

Causal Inference 360 A Python package for inferring causal effects from observational data. Description Causal inference analysis enables estimating t

International Business Machines 506 Dec 19, 2022
Meltano: ELT for the DataOps era. Meltano is open source, self-hosted, CLI-first, debuggable, and extensible.

Meltano is open source, self-hosted, CLI-first, debuggable, and extensible. Pipelines are code, ready to be version c

Meltano 625 Jan 02, 2023
A data parser for the internal syncing data format used by Fog of World.

A data parser for the internal syncing data format used by Fog of World. The parser is not designed to be a well-coded library with good performance, it is more like a demo for showing the data struc

Zed(Zijun) Chen 40 Dec 12, 2022
Desafio 1 ~ Bantotal

Challenge 01 | Bantotal Please read the instructions for the challenge by selecting your preferred language below: Español Português License Copyright

Maratona Behind the Code 44 Sep 28, 2022
Orchest is a browser based IDE for Data Science.

Orchest is a browser based IDE for Data Science. It integrates your favorite Data Science tools out of the box, so you don’t have to. The application is easy to use and can run on your laptop as well

Orchest 3.6k Jan 09, 2023
A python package which can be pip installed to perform statistics and visualize binomial and gaussian distributions of the dataset

GBiStat package A python package to assist programmers with data analysis. This package could be used to plot : Binomial Distribution of the dataset p

Rishikesh S 4 Oct 17, 2022
Fit models to your data in Python with Sherpa.

Table of Contents Sherpa License How To Install Sherpa Using Anaconda Using pip Building from source History Release History Sherpa Sherpa is a modeli

134 Jan 07, 2023
PCAfold is an open-source Python library for generating, analyzing and improving low-dimensional manifolds obtained via Principal Component Analysis (PCA).

PCAfold is an open-source Python library for generating, analyzing and improving low-dimensional manifolds obtained via Principal Component Analysis (PCA).

Burn Research 4 Oct 13, 2022
Data Competition: automated systems that can detect whether people are not wearing masks or are wearing masks incorrectly

Table of contents Introduction Dataset Model & Metrics How to Run Quickstart Install Training Evaluation Detection DATA COMPETITION The COVID-19 pande

Thanh Dat Vu 1 Feb 27, 2022
OpenARB is an open source program aiming to emulate a free market while encouraging players to participate in arbitrage in order to increase working capital.

Overview OpenARB is an open source program aiming to emulate a free market while encouraging players to participate in arbitrage in order to increase

Tom 3 Feb 12, 2022
Validated, scalable, community developed variant calling, RNA-seq and small RNA analysis

Validated, scalable, community developed variant calling, RNA-seq and small RNA analysis. You write a high level configuration file specifying your in

Blue Collar Bioinformatics 917 Jan 03, 2023
Amundsen is a metadata driven application for improving the productivity of data analysts, data scientists and engineers when interacting with data.

Amundsen is a metadata driven application for improving the productivity of data analysts, data scientists and engineers when interacting with data.

Amundsen 3.7k Jan 03, 2023
Spectral Analysis in Python

SPECTRUM : Spectral Analysis in Python contributions: Please join https://github.com/cokelaer/spectrum contributors: https://github.com/cokelaer/spect

Thomas Cokelaer 280 Dec 16, 2022
wikirepo is a Python package that provides a framework to easily source and leverage standardized Wikidata information

Python based Wikidata framework for easy dataframe extraction wikirepo is a Python package that provides a framework to easily source and leverage sta

Andrew Tavis McAllister 35 Jan 04, 2023
This cosmetics generator allows you to generate the new Fortnite cosmetics, Search pak and search cosmetics!

COSMETICS GENERATOR This cosmetics generator allows you to generate the new Fortnite cosmetics, Search pak and search cosmetics! Remember to put the l

ᴅᴊʟᴏʀ3xᴢᴏ 11 Dec 13, 2022
Flexible HDF5 saving/loading and other data science tools from the University of Chicago

deepdish Flexible HDF5 saving/loading and other data science tools from the University of Chicago. This repository also host a Deep Learning blog: htt

UChicago - Department of Computer Science 255 Dec 10, 2022