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
CaterApp is a cross platform, remotely data sharing tool created for sharing files in a quick and secured manner.

CaterApp is a cross platform, remotely data sharing tool created for sharing files in a quick and secured manner. It is aimed to integrate this tool with several more features including providing a U

Ravi Prakash 3 Jun 27, 2021
The lastest all in one bombing tool coded in python uses tbomb api

BaapG-Attack is a python3 based script which is officially made for linux based distro . It is inbuit mass bomber with sms, mail, calls and many more bombing

59 Dec 25, 2022
Python library for creating data pipelines with chain functional programming

PyFunctional Features PyFunctional makes creating data pipelines easy by using chained functional operators. Here are a few examples of what it can do

Pedro Rodriguez 2.1k Jan 05, 2023
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
Universal data analysis tools for atmospheric sciences

U_analysis Universal data analysis tools for atmospheric sciences Script written in python 3. This file defines multiple functions that can be used fo

Luis Ackermann 1 Oct 10, 2021
Gathering data of likes on Tinder within the past 7 days

tinder_likes_data Gathering data of Likes Sent on Tinder within the past 7 days. Versions November 25th, 2021 - Functionality to get the name and age

Alex Carter 12 Jan 05, 2023
Pyspark Spotify ETL

This is my first Data Engineering project, it extracts data from the user's recently played tracks using Spotify's API, transforms data and then loads it into Postgresql using SQLAlchemy engine. Data

16 Jun 09, 2022
A pipeline that creates consensus sequences from a Nanopore reads. I

A pipeline that creates consensus sequences from a Nanopore reads. It clusters reads that are similar to each other and creates a consensus that is then identified using BLAST.

Ada Madejska 2 May 15, 2022
pandas: powerful Python data analysis toolkit

pandas is a Python package that provides fast, flexible, and expressive data structures designed to make working with "relational" or "labeled" data both easy and intuitive.

pandas 36.4k Jan 03, 2023
Synthetic data need to preserve the statistical properties of real data in terms of their individual behavior and (inter-)dependences

Synthetic data need to preserve the statistical properties of real data in terms of their individual behavior and (inter-)dependences. Copula and functional Principle Component Analysis (fPCA) are st

32 Dec 20, 2022
Randomisation-based inference in Python based on data resampling and permutation.

Randomisation-based inference in Python based on data resampling and permutation.

67 Dec 27, 2022
Cleaning and analysing aggregated UK political polling data.

Analysing aggregated UK polling data The tweet collection & storage pipeline used in email-service is used to also collect tweets from @britainelects.

Ajay Pethani 0 Dec 22, 2021
PySpark Structured Streaming ROS Kafka ApacheSpark Cassandra

PySpark-Structured-Streaming-ROS-Kafka-ApacheSpark-Cassandra The purpose of this project is to demonstrate a structured streaming pipeline with Apache

Zekeriyya Demirci 5 Nov 13, 2022
Generate lookml for views from dbt models

dbt2looker Use dbt2looker to generate Looker view files automatically from dbt models. Features Column descriptions synced to looker Dimension for eac

lightdash 126 Dec 28, 2022
The official pytorch implementation of ViTAE: Vision Transformer Advanced by Exploring Intrinsic Inductive Bias

ViTAE: Vision Transformer Advanced by Exploring Intrinsic Inductive Bias Introduction | Updates | Usage | Results&Pretrained Models | Statement | Intr

104 Nov 27, 2022
Zipline, a Pythonic Algorithmic Trading Library

Zipline is a Pythonic algorithmic trading library. It is an event-driven system for backtesting. Zipline is currently used in production as the backte

Quantopian, Inc. 15.7k Jan 07, 2023
Intake is a lightweight package for finding, investigating, loading and disseminating data.

Intake: A general interface for loading data Intake is a lightweight set of tools for loading and sharing data in data science projects. Intake helps

Intake 851 Jan 01, 2023
Helper tools to construct probability distributions built from expert elicited data for use in monte carlo simulations.

Elicited Helper tools to construct probability distributions built from expert elicited data for use in monte carlo simulations. Credit to Brett Hoove

Ryan McGeehan 3 Nov 04, 2022
University Challenge 2021 With Python

University Challenge 2021 This repository contains: The TeX file of the technical write-up describing the University / HYPER Challenge 2021 under late

2 Nov 27, 2021
MetPy is a collection of tools in Python for reading, visualizing and performing calculations with weather data.

MetPy MetPy is a collection of tools in Python for reading, visualizing and performing calculations with weather data. MetPy follows semantic versioni

Unidata 971 Dec 25, 2022