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
Very useful and necessary functions that simplify working with data

Additional-function-for-pandas Very useful and necessary functions that simplify working with data random_fill_nan(module_name, nan) - Replaces all sp

Alexander Goldian 2 Dec 02, 2021
Code for the DH project "Dhimmis & Muslims – Analysing Multireligious Spaces in the Medieval Muslim World"

Damast This repository contains code developed for the digital humanities project "Dhimmis & Muslims – Analysing Multireligious Spaces in the Medieval

University of Stuttgart Visualization Research Center 2 Jul 01, 2022
A real data analysis and modeling project - restaurant inspections

A real data analysis and modeling project - restaurant inspections Jafar Pourbemany 9/27/2021 This project represents data analysis and modeling of re

Jafar Pourbemany 2 Aug 21, 2022
Python dataset creator to construct datasets composed of OpenFace extracted features and Shimmer3 GSR+ Sensor datas

Python dataset creator to construct datasets composed of OpenFace extracted features and Shimmer3 GSR+ Sensor datas

Gabriele 3 Jul 05, 2022
Analyze the Gravitational wave data stored at LIGO/VIRGO observatories

Gravitational-Wave-Analysis This project showcases how to analyze the Gravitational wave data stored at LIGO/VIRGO observatories, using Python program

1 Jan 23, 2022
yt is an open-source, permissively-licensed Python library for analyzing and visualizing volumetric data.

The yt Project yt is an open-source, permissively-licensed Python library for analyzing and visualizing volumetric data. yt supports structured, varia

The yt project 367 Dec 25, 2022
Exploring the Top ML and DL GitHub Repositories

This repository contains my work related to my project where I scraped data on the most popular machine learning and deep learning GitHub repositories in order to further visualize and analyze it.

Nico Van den Hooff 17 Aug 21, 2022
scikit-survival is a Python module for survival analysis built on top of scikit-learn.

scikit-survival scikit-survival is a Python module for survival analysis built on top of scikit-learn. It allows doing survival analysis while utilizi

Sebastian Pölsterl 876 Jan 04, 2023
Streamz helps you build pipelines to manage continuous streams of data

Streamz helps you build pipelines to manage continuous streams of data. It is simple to use in simple cases, but also supports complex pipelines that involve branching, joining, flow control, feedbac

Python Streamz 1.1k Dec 28, 2022
Recommendations from Cramer: On the show Mad-Money (CNBC) Jim Cramer picks stocks which he recommends to buy. We will use this data to build a portfolio

Backtesting the "Cramer Effect" & Recommendations from Cramer Recommendations from Cramer: On the show Mad-Money (CNBC) Jim Cramer picks stocks which

Gábor Vecsei 12 Aug 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
Modular analysis tools for neurophysiology data

Neuroanalysis Modular and interactive tools for analysis of neurophysiology data, with emphasis on patch-clamp electrophysiology. Functions for runnin

Allen Institute 5 Dec 22, 2021
A computer algebra system written in pure Python

SymPy See the AUTHORS file for the list of authors. And many more people helped on the SymPy mailing list, reported bugs, helped organize SymPy's part

SymPy 9.9k Dec 31, 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
A Numba-based two-point correlation function calculator using a grid decomposition

A Numba-based two-point correlation function (2PCF) calculator using a grid decomposition. Like Corrfunc, but written in Numba, with simplicity and hackability in mind.

Lehman Garrison 3 Aug 24, 2022
Conduits - A Declarative Pipelining Tool For Pandas

Conduits - A Declarative Pipelining Tool For Pandas Traditional tools for declaring pipelines in Python suck. They are mostly imperative, and can some

Kale Miller 7 Nov 21, 2021
Tools for the analysis, simulation, and presentation of Lorentz TEM data.

ltempy ltempy is a set of tools for Lorentz TEM data analysis, simulation, and presentation. Features Single Image Transport of Intensity Equation (SI

McMorran Lab 1 Dec 26, 2022
Stochastic Gradient Trees implementation in Python

Stochastic Gradient Trees - Python Stochastic Gradient Trees1 by Henry Gouk, Bernhard Pfahringer, and Eibe Frank implementation in Python. Based on th

John Koumentis 2 Nov 18, 2022
pyETT: Python library for Eleven VR Table Tennis data

pyETT: Python library for Eleven VR Table Tennis data Documentation Documentation for pyETT is located at https://pyett.readthedocs.io/. Installation

Tharsis Souza 5 Nov 19, 2022
An ETL framework + Monitoring UI/API (experimental project for learning purposes)

Fastlane An ETL framework for building pipelines, and Flask based web API/UI for monitoring pipelines. Project structure fastlane |- fastlane: (ETL fr

Dan Katz 2 Jan 06, 2022