In [25]:
import numpy as np
from collections.abc import Iterable
from typing import List
from pydantic import (
BaseModel, validator, root_validator,
PositiveFloat, confloat
)
In [18]:
class A(BaseModel):
x: int
class B(A):
y: int
In [19]:
class Vector(BaseModel):
r: PositiveFloat
θ: confloat(gt=0, lt=2*np.pi)
In [20]:
Vector.schema()
Out[20]:
In [21]:
class Complex(Vector):
@validator('θ', pre=True)
def standardize_θ(θ):
return θ % (2*np.pi)
def conj(self):
return Complex(r=self.r, θ=-self.θ)
z = Complex(r=1, θ=0.75)
z.conj()
Out[21]:
In [22]:
class VectorBasis(BaseModel):
e :List[Vector]
basis = VectorBasis(e=[z, z.conj()])
basis
Out[22]:
In [13]:
class A:
def __init__(self, x:int):
self.x = x
class B(A):
def __init__(self, x:int, y:int):
super().__init__(x)
# Remove y from signature
self.y
In [14]:
class Vector:
def __init__(self, r:float, θ:float):
if r <= 0:
raise ValueError("Negative radius")
if θ < 0 or 2*np.pi < θ:
raise ValueError("Angle outside [0,2π]")
self.r = r
self.θ = θ
In [15]:
class Complex(Vector):
def __init__(self, r:float, θ:float):
θ = θ % (2*np.pi)
super().__init__(r, θ)
def conj(self):
return Complex(self.r, -self.θ)
z = Complex(r=1, θ=0.75)
z.conj()
Out[15]:
In [16]:
class VectorBasis:
def __init__(self, e):
if not isinstance(e, Iterable):
raise TypeError(
"e is not iterable")
if not isinstance(e, list):
e = list(e)
for ei in e:
if not isinstance(ei, Vector):
raise TypeError(
"e must be composed of Vector objects")
self.e = e
basis = VectorBasis([z, z.conj()])
basis
Out[16]:
In [23]:
Vector(r=-1, θ=99)
In [26]:
class Foo(BaseModel):
a: int
b: int
@root_validator
def root_val_post(cls, values):
print("root val post")
return values
@root_validator(pre=True)
def root_val_pre(cls, values):
print("root val pre")
return values
@validator('a')
def val_post_a(cls, a):
print("val post a")
return a
@validator('b', pre=True)
def val_pre_b(cls, b):
print("val pre b")
return b
@validator('a', pre=True)
def val_pre_a(cls, a):
print("val pre a")
return a
@validator('b')
def val_post_b(cls, b):
print("val post b")
return b
In [28]:
Foo(a=1, b=1)
Out[28]:
In [29]:
Foo()
In [30]:
Foo(a=[1,2], b=1)
In [31]:
Foo(a=1, b=[1,2])
In [32]:
Foo(a=[1,2], b=[1,2])
In [ ]: