Saravanan666/pypi-org huggingface dataset:
Package: pydantic-avro
pydantic-avroThis library can convert a pydantic class to a avro schema or generate python code from a avro schema.Installpipinstallpydantic-avroPydantic class to avro schemaimportjsonfromtypingimportOptionalfrompydantic_avro.baseimportAvroBaseclassTestModel(AvroBase):key1:strkey2:intkey2:Optional[str]schema_dict:dict=TestModel.avro_schema()print(json.dumps(schema_dict))Avro schema to pydantic# Print to stdoutpydantic-avroavro_to_pydantic--asvc/path/to/schema.asvc# Save it to a filepydantic-avroavro_to_pydantic--asvc/path/to/schema.asvc--output/path/to/output.pyInstall for developersInstall packageRequirement: Poetry 1.*poetryinstallRun unit testspytest
coveragerun-mpytest# with coverage# or (depends on your local env)poetryrunpytest
poetryruncoveragerun-mpytest# with coverageRun lintingThe linting is checked in the github workflow. To fix and review issues run this:black.# Auto fix all issuesisort.# Auto fix all issuespflake.# Only display issues, fixing is manual
Package: pydantic-azure-secrets
pydantic-azure-secretsA class to use pydantic settings together withAzure KeyVaultThebehaviourof the class is exactly like inpydantic.BaseSettings, except the step which checks azure key vault:settings_args > envs > dotenv > secret_directory > azure_keyvault > defaultsInstall:pipinstallpydantic-azure-secretsExample:# Example for GitHub REST APIfrompydanticimportHttpUrl,SecretStrfrompydantic_azure_secretsimportAzureVaultSettingsclassGitHubBasic(AzureVaultSettings):url:HttpUrl="https://api.github.com/user"username:strtoken:SecretStrclassConfig:env_prefix="github_"azure_keyvault=<your_keyvault_URI># e.g. "https://pydantic-test-kv.vault.azure.net/"github_settings=GitHubBasic()# GitHubBasic(url=HttpUrl('https://github.com', scheme='https', host='github.com', tld='com', host_type='domain'), username='kewtree1408', token=SecretStr('**********'))See more examples in theexample.pyAuthentificationAuthentification for azure keyvault is the same as forSDKBefore using the library, please log in to your Azure subscription with one of the following methodsaz loginenvironment variables:AZURE_CLIENT_ID,AZURE_CLIENT_PASSWORD,AZURE_TENANT_IDsee moreRun teststoxTODO:support custom chain authentification for Azure:example1,example2
Package: pydantic-base-aiogram
Pydantic-base-aiogramThis code simplifies the conversion of Pydantic schemas into Aiogram handler groups,
making it easy to create form-filling handlers.Installationpipinstallpydantic_base_aiogramUsage:>>>fromenumimportEnum>>>fromtypingimportUnion>>>frompydanticimportBaseModel>>>frompydantic_base_aiogramimportSchemaBaseHandlersGroup# ----------------------------------------utils-methods-------------------------------------->>>defcheck_for_properties_existense(cls,properties:list[str]):...dirs=dir(cls)...assertlen(tuple(filter(lambdax:notxindirs,properties)))==0...assertcls(finish_call=None)# ----------------------------------------Simple datatypes schema-------------------------------------->>>classPersonPydanticFormSchema(BaseModel):...name:str...age:int...height:float...>>>classPersonFormHanlders(SchemaBaseHandlersGroup[PersonPydanticFormSchema]):...pass......>>>check_for_properties_existense(PersonFormHanlders,['name_view','age_view','height_view'])# ----------------------------------------Enum datatype schema----------------------------------------->>>classMood(Enum):...HAPPY="😄 Happy"...SAD="😢 Sad"...EXCITED="🤩 Excited"...RELAXED="😌 Relaxed"...>>>>>>>>>classPersonMoodPydanticFormSchema(BaseModel):...name:str...current_mood:Mood...>>>classPersonMoodFormHanlders(SchemaBaseHandlersGroup[PersonMoodPydanticFormSchema]):...pass......>>>check_for_properties_existense(PersonMoodFormHanlders,['name_view','current_mood_view'])# ----------------------------------------Complex schema----------------------------------------------->>>classAddress(BaseModel):...street:str...city:str...postal_code:str...>>>classPerson(BaseModel):...name:str...age:int...address:Address......>>>classPersonFormHanlders(SchemaBaseHandlersGroup[Person]):...pass......>>>check_for_properties_existense(...PersonFormHanlders,...[...'name_view',...'address_street_view',...'address_city_view',...'address_postal_code_view'...]...)...# ------------------------------------Combined Enum datatype schema------------------------------------>>>classHappyMood(Enum):...HAPPY="😄 Happy"...>>>classSadMood(Enum):...SAD="😢 Sad"...>>>classExcitedMood(Enum):...EXCITED="🤩 Excited"...>>>classRelaxedMood(Enum):...RELAXED="😌 Relaxed"...>>>>>>classPersonMoodPydanticFormSchema(BaseModel):...name:str...current_mood:Union[HappyMood,SadMood,ExcitedMood,RelaxedMood]...future_mood:HappyMood|SadMood|ExcitedMood|RelaxedMood......>>>classPersonMoodFormHanlders(SchemaBaseHandlersGroup[PersonMoodPydanticFormSchema]):...pass......>>>check_for_properties_existense(PersonMoodFormHanlders,['name_view','current_mood_view'])
Package: pydantic-br
Pydantic BREssa é uma biblioteca de extensão e visa disponibilizar campos com validações brasileiras para a biblioteca pydantic.Compatível com a versão v1 e v2 do Pydantic.Código fonte:https://github.com/scjorge/pydantic_brDocumentação:https://pydantic-br.readthedocs.ioDisponibilidadesCampoGrupo de DocumentosNome do DocumentoMétodo de validaçãoSituaçãoCNPJPessoa JurídicaCarteira Nacional de Pessoas JurídicasDigito VerificadorConcluídoCPFPessoa físicaCadastro de Pessoa FísicaDigito VerificadorConcluídoCNHPessoa físicaCarteira Nacional de HabilitaçãoDigito VerificadorConcluídoTEPessoa físicaTítulo de EleitorDigito VerificadorConcluídoPISPessoa físicaPrograma de Integração SocialDigito VerificadorConcluídoCERTPessoa físicaCertidão (Nascimento/Casamento/Óbito)Digito VerificadorConcluídoCNSPessoa físicaCartão Nacional de SaúdeDigito VerificadorEm desenvolvimentoRENAVAMVeículosRegistro Nacional de Veículos AutomotoresRegExrEm desenvolvimentoPLACAVeículosPlaca do VeículoRegExrEm desenvolvimentoISBNLivrosPadrão Internacional de Numeração de LivroDigito VerificadorEm desenvolvimentoInstalaçãoUtilizando pippip install pydantic-brUtilizando Poetrypoetry add pydantic-brExemplos de UtilizaçãoOs exemplos de dados exemplificados foram tirados dos seguintes sites:geradordecpf4devsA má utilização dos dados é de total responsabilidade do usuário.CPF válidofrompprintimportpprintfrompydanticimportBaseModelfrompydantic_brimportCPF,CPFDigits,CPFMaskclassPessoa(BaseModel):nome:strcpf:CPF# aceita CPF válidos com ou sem máscaracpf_mask:CPFMask# aceita CPF válido apenas com máscaracpf_digits:CPFDigits# aceita CPF válido apnas com dígitosp1=Pessoa(nome="João",cpf="53221394780",cpf_mask="532.213.947-80",cpf_digits="53221394780")pprint(p1.dict())Saída{'cpf': '53221394780',
 'cpf_digits': '53221394780',
 'cpf_mask': '532.213.947-80',
 'nome': 'João'}CPF inválidofrompprintimportpprintfrompydanticimportBaseModelfrompydantic_brimportCPF,CPFDigits,CPFMaskclassPessoa(BaseModel):nome:strcpf:CPF# aceita CPF válidos com ou sem máscaracpf_mask:CPFMask# aceita CPF válido apenas com máscaracpf_digits:CPFDigits# aceita CPF válido apenas com dígitosp1=Pessoa(nome="João",cpf="00000000000",cpf_mask="53221394780",cpf_digits="532.213.947-80")pprint(p1.dict())SaídaTraceback (most recent call last):
    p1 = Pessoa(
  File "pydantic\main.py", line 341, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 3 validation errors for Pessoa
cpf
  invalid data (type=value_error.invalid_data)
cpf_mask
  invalid mask format (type=value_error.invalid_mask)
cpf_digits
  field only accept digits as string (type=value_error.not_digits)Versões do PydanticOs exemplos acima estão escritos na versão v1 do Pydantic. Entretanto, funciona perfeitamente com a versão v2.Então que mudará? Bem, os métodos de 'apresentação' das models foram alterados na v2.O métododict()foi alterado paramodel_dump()O métodoschema()foi alterado paramodel_json_schema()
Package: pydantic-br-validator
Pydantic BR ValidatorUma biblioteca python com modelos de validação para os principais documentos brasileiros.Instalaçãopipinstallpydantic_br_validatorCampos disponíveisCPFfrompprintimportpprintfrompydanticimportBaseModelfrompydantic_br_validatorimportCPF,CPFDigits,CPFMaskclassCliente(BaseModel):nome:strcpf:CPF# aceita CPF válidos com ou sem máscaracpf_mask:CPFMask# aceita CPF válido apenas com máscaracpf_digits:CPFDigits# aceita CPF válido apenas com dígitoscliente=Cliente(nome="Hudson",cpf="04120039021",cpf_mask="041.200.390-21",cpf_digits="04120039021")pprint(cliente.dict())CNPJfrompprintimportpprintfrompydanticimportBaseModelfrompydantic_br_validatorimportCNPJ,CNPJDigits,CNPJMaskclassCliente(BaseModel):nome:strcnpj:CNPJ# aceita CNPJ válidos com ou sem máscaracnpj_mask:CNPJMask# aceita CNPJ válido apenas com máscaracnpj_digits:CNPJDigits# aceita CNPJ válido apnas com dígitoscliente=Cliente(nome="Hudson",cnpj="47895328000187",cnpj_mask="47.895.328/0001-87",cnpj_digits="47895328000187")pprint(cliente.dict())Contribua 🚀
Package: pydantic-cereal
pydantic-cerealAdvanced serialization for Pydantic modelsPydanticis the most widely used data validation library for Python.
It uses type hints/type annotations to define data models and has quite a nice "feel" to it.
Pydantic V2 wasreleased in June 2023and
brings many changes and improvements, including anew Rust-based engine for serializing and validating data.This package,pydantic-cereal, is a small extension package that enables users to serialize Pydantic
models with "arbitrary" (non-JSON-fiendly) types to "arbitrary" file-system-like locations.
It usesfsspecto support generic file systems.
Writing a custom writer (serializer) and reader (loader) withfsspecURIs is quite straightforward.
You can also useuniversal-pathlib'sUPathwithpydantic-cereal.📘 See thefull documentation here. 📘Usage ExampleSee theminimal pure-Python exampleto learn how to wrap your own type.
Below is a preview of this example.fromfsspecimportAbstractFileSystemfrompydanticimportBaseModel,ConfigDictfrompydantic_cerealimportCerealcereal=Cereal()# This is a global variable# Create and "register" a custom typeclassMyType(object):"""My custom type, which isn't a Pydantic model."""def__init__(self,value:str):self.value=str(value)def__repr__(self)->str:returnf"MyType({self.value})"defmy_reader(fs:AbstractFileSystem,path:str)->MyType:"""Read a MyType from an fsspec URI."""returnMyType(value=fs.read_text(path))# type: ignoredefmy_writer(obj:MyType,fs:AbstractFileSystem,path:str)->None:"""Write a MyType object to an fsspec URI."""fs.write_text(path,obj.value)MyWrappedType=cereal.wrap_type(MyType,reader=my_reader,writer=my_writer)# Use type within Pydantic modelclassMyModel(BaseModel):"""My custom Pydantic model."""config=ConfigDict(arbitrary_types_allowed=True)# Pydantic configurationfld:MyWrappedTypemdl=MyModel(fld=MyType("my_field"))# We can save the whole model to an fsspec URI, such as this MemoryFileSystemuri="memory://my_model"cereal.write_model(mdl,uri)# And we can read it back laterobj=cereal.read_model(uri)assertisinstance(obj,MyModel)assertisinstance(obj.fld,MyType)For wrapping 3rd-party libraries, see thePandas dataframe example.
Package: pydantic-choices
Pydantic-ChoicesHow to usefrompydantic_choicesimportchoiceimportpydanticaspdLicenses=choice(["GPL","GPLv3+","MIT","MPL 2.0"])classProject(pd.BaseModel):id:strurl:strlicense:Licenses# Validation passesProject(id="pydantic_choices",url="https://github.com/vinissimus/pydantic-choices",license="MIT",)# Validation failsp1=Project(id="pydantic_choices",url="https://github.com/vinissimus/pydantic-choices",license="propietary",# value not in choice)
Package: pydantic-cidoc-crm
Pydantic Cidoc-CRM ImplementationA Python implementation ofCidoc-CRM 7.1.1usingpydanticandrdflib.Data modelling in conformity with Cidoc-CRM poses some challenges. Cidoc-CRM has a complex inheritance structure, from which specific range and domain restrictions are derived. Complying with these restrictions can be difficult at times. This package is an attempt to facilitate working with Cidoc-CRM in Python, as well as mitigate some of its challenges. By means of rigours type checking, domain and range are ensured to be correct at all times, as well as typos prevented that would hinder interoperability.To conform to Python's syntax and standards, a few name changes had to be made:Underscores and dashes in class names are omitted (E24_Physical_Human-Made_Thing -> E24PhysicalHumanMadeThing)All properties start with a lower p (P1_is_identified_by -> p1_is_identified_by)Dashes in property names are replaced by underscores (P4_has_time-span -> p4_has_time_span)However, when an object is serialized, all names are converted back.LimitationsCardinality and XSD types are not defined in the RDFS files. Since this model is automatically generated from theses files, they are not implemented here either. For now, every property accepts an instance or a list of instances of the required domain class or one of its subclasses.Installation$pip3installpydantic_cidoc_crmUsagefrompydantic_cidoc_crmimportE53Place,E41Appellationx=E53Place(iri="http:/localhost/a_place",p1_is_identified_by=E41Appellation(iri="http:/localhost/a_place/appellation",p190_has_symbolic_content=["Berlin"]))x.serialize()<http:/localhost/a_place/appellation> <http://www.cidoc-crm.org/cidoc-crm/P190_has_symbolic_content> "Berlin" .<http:/localhost/a_place/appellation> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.cidoc-crm.org/cidoc-crm/E41_Appellation> .<http:/localhost/a_place> <http://www.cidoc-crm.org/cidoc-crm/P1_is_identified_by> <http:/localhost/a_place/appellation> .<http:/localhost/a_place> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.cidoc-crm.org/cidoc-crm/E53_Place>Restrictions of domain:frompydantic_cidoc_crmimportE53Place,E41Appellationx=E53Place(iri="http:/localhost/a_place",p48_has_preferred_identifier=E41Appellation(iri="http:/localhost/a_place/identifier",p190_has_symbolic_content="123"))Will throw a validation error:pydantic.error_wrappers.ValidationError: 1 validation error for E53Placep48_has_preferred_identifierDomain must be E42Identifier or a subclass of it. (type=value_error)Restriction of range and safeguard against typos:frompydantic_cidoc_crmimportE53Place,E41Appellationx=E53Place(iri="http:/localhost/a_place",p1_is_identefied_by=E41Appellation(iri="http:/localhost/a_place/appellation",p190_has_symbolic_content="Berlin"))Will throw a validation error:pydantic.error_wrappers.ValidationError: 1 validation error for E53Placep1_is_identefied_byextra fields not permitted (type=value_error.extra)LicenseThis project is licensed under MIT license - see theLICENSEfile for more information.
Package: pydantic-client
pydantic-clientHttp client base pydantic, with requests or aiohttpHow to installonly support requests:pip install pydantic-clientsupport aiohttp and requests:pip install pydantic-client[aiohttp]support httpx and requests:pip install pydantic-client[httpx]support all:pip install pydantic-client[all]How to usefrompydanticimportBaseModelfrompydantic_clientimportdelete,get,post,putfrompydantic_client.clients.requestsimportRequestsClientclassBook(BaseModel):name:strage:intclassR(RequestsClient):@get("/books/{book_id}?query={query}")defget_book(self,book_id:int,query:str)->Book:...@post("/books",form_body=True)defcreate_book_form(self,book:Book)->Book:""" will post the form with book"""...@put("/books/{book_id}")defchange_book(self,book_id:int,book:Book)->Book:"""will put the json body"""...@delete("/books/{book_id}")defchange_book(self,book_id:int)->Book:...my_client=R("http://localhost/v1")get_book:Book=my_client.get_book(1)The Groupfrompydantic_clientimportGroupfrompydantic_client.clients.requestsimportRequestsClientgroup=Group("/book")person_group=Group("/person")classGroupClient(RequestsClient):def__init__(self):super().__init__("http://localhost")@group.get("/{book_id}")defget(self,book_id:int)->Book:# type: ignore...@person_group.get("/{person_id}")defget_person(self,person_id:int)->Person:# type: ignore...client=GroupClient()book=client.get(1)person=client.get_person(1)
Package: pydantic-cli-model
Pydantic CLI ModelsPydantic + Click == Perfection (with love to Rust'sclaplibrary)GithubIssuesReduce boilerplate by 2x (at least), turning this:importclickfrompydanticimportBaseModelclassPerson(BaseModel):name:strage:int@click.command()@click.option("--name",type=str)@click.option("--age",type=int)defmain(name,age):person=Person(name=name,age=age)# ... do something with person ...Into this:frompydantic_cli_modelimportCLIModelclassPerson(CLIModel):name:strage:int@Person.clidefmain(person:Person):...# ... do something with person ...And get data validation for free!
Package: pydantic-cloud-configuration
Pydantic Cloud ConfigurationFeaturesPydantic Cloud Configuration simplifies the retrieval of settings from the AWS cloud based on conventions.RequirementsPython 3.6+ required.InstallationYou can installPydantic Cloud ConfigurationviapipfromPyPI:$pipinstallpydantic-cloud-configurationUsagePlease see theCommand-line Referencefor details.ContributingContributions are very welcome.
To learn more, see theContributor Guide.LicenseDistributed under the terms of theMIT license,Pydantic Cloud Settingsis free and open source software.IssuesIf you encounter any problems,
pleasefile an issuealong with a detailed description.CreditsThis project was generated from@cjolowicz'sHypermodern Python Cookiecuttertemplate.
Package: pydantic-collection
pydantic-collection - Collections of pydantic modelpydantic-collection is collections of pydantic modelModelsThis project is an experimental phase.Warning: Some interface will be changed.How to installpydantic-collection requires Python 3.8.0 or later$pipinstallpydantic-collectionContributing to pydantic-collectionWe are waiting for your contributions topydantic-collection.How to contributehttps://koxudaxi.github.io/pydantic-collection/contributingPyPihttps://pypi.org/project/pydantic-collectionSource Codehttps://github.com/koxudaxi/pydantic-collectionDocumentationhttps://koxudaxi.github.io/pydantic-collectionLicensepydantic-collection is released under the MIT License.http://www.opensource.org/licenses/mit-license
Package: pydantic-collections
pydantic-collectionsThepydantic-collectionspackage providesBaseCollectionModelclass that allows you
to manipulate collections ofpydanticmodels
(and any other types supported by pydantic).RequirementsPython>=3.7pydantic>=1.8.2,<3.0Installationpip install pydantic-collectionsUsageBasic usagefromdatetimeimportdatetimefrompydanticimportBaseModelfrompydantic_collectionsimportBaseCollectionModelclassUser(BaseModel):id:intname:strbirth_date:datetimeclassUserCollection(BaseCollectionModel[User]):passuser_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())# pydantic v1.xprint(users.model_dump())# pydantic v2.x#> [{'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())# pydantic v1.xprint(users.model_dump_json())# pydantic v2.x#> [{"id": 1, "name": "Bender", "birth_date": "2010-04-01T12:59:59"}, {"id": 2, "name": "Balaganov", "birth_date": "2020-04-01T12:59:59"}]Strict assignment validationBy defaultBaseCollectionModelhas a strict assignment check...users=UserCollection()users.append(User(id=1,name='Bender',birth_date=datetime.utcnow()))# OKusers.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 ConfigPydantic v1.xfrompydantic_collectionsimportBaseCollectionModel...classUserCollection(BaseCollectionModel[User]):classConfig:validate_assignment_strict=FalsePydantic v2.xfrompydantic_collectionsimportBaseCollectionModel,CollectionModelConfig...classUserCollection(BaseCollectionModel[User]):model_config=CollectionModelConfig(validate_assignment_strict=False)users=UserCollection()users.append({'id':1,'name':'Bender','birth_date':'2010-04-01T12:59:59'})# OKassertusers[0].__class__isUserassertusers[0].id==1Using as a model fieldBaseCollectionModelis a subclass ofBaseModel, so you can use it as a model field...classUserContainer(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(...))...
Package: pydantic-computed
pydantic-computedA new decorator for pydantic allowing you to define dynamic fields that are computed from other properties.InstallationInstall the package by runningpipinstallpydantic_computedExamples and use casesA computed integer propertyfrompydanticimportBaseModelfrompydantic_computedimportComputed,computedclassComputedModelInt(BaseModel):a:intb:intc:Computed[int]@computed('c')defcalculate_c(a:int,b:int,**kwargs):returna+bmodel=ComputedModelInt(a=1,b=2)print(model.c)# Outputs 3Multiple computed propertiesfrompydanticimportBaseModelfrompydantic_computedimportComputed,computedclassMultipleComputed(BaseModel):a:intb:intc:Computed[int]d:Computed[int]e:Computed[int]@computed('c')defcalc_c(a:int,b:int,**kwargs):returna+b@computed('d')defcalc_d(c:int,**kwargs):# Note that property d uses the value of the computed property c (The order of declaration matters!)returnc*2model=MultipleComputed(a=1,b=2)print(model.c)# Outputs 3print(model.d)# Outputs 6Since all properties are passed as **kwargs to calculate_c, we can use the property names for the parametersComplex typesSuppose you set up a FastAPI application where you have users and orders stored in a database.
All Models in the database have an automatically generated id.
Now you want to be able to dynamically generate links to those objects.
E.g. the user with id=3 is accessible on the endpointhttp://my-api/users/3Instead of storing those links in the database you can simply generate them with the computed decorator.
example:frompydanticimportBaseModel,Fieldfrompydantic_computedimportComputed,computedclassLink(BaseModel):href:strmethod:strclassSchemaLinked(BaseModel):id:intbase_url:strlink:Computed[Link]@computed('link')defcompute_link(id:int,base_url:str,**kwargs):returnLink(href=f'{base_url}/{id}',method='GET')classUser(SchemaLinked):base_url:str=Field('/users',exclude=True)username:strclassOrder(SchemaLinked):base_url:str=Field('/orders',exclude=True)user:Useruser=User(id=3,username='exampleuser')user.json()"""{id: 3,username: "exampleuser",link: {href: "/users/3",method: "GET"}}"""order=Order(id=2,user=user)order.json()"""{id: 2,link: {href: "/orders/2",method: "GET"},user: {id: 3,username: "exampleuser",link: {href: "/users/3",method: "GET"}}}"""Vector example:frompydanticimportBaseModelfrompydantic_computedimportcomputed,ComputedimportmathclassPoint(BaseModel):x:inty:intclassVector(BaseModel):p1:Pointp2:Pointx:Computed[float]y:Computed[float]weight:Computed[float]@computed('x')defcompute_x(p1:Point,p2:Point,**kwargs):returnp2.x-p1.x@computed('y')defcompute_y(p1:Point,p2:Point,**kwargs):returnp2.y-p1.y@computed('weight')defcompute_weight(x:float,y:float,**kwargs):returnmath.sqrt(x**2+y**2)v1=Vector(p1=Point(x=0,y=0),p2=Point(x=1,y=0))print(v1.weight)# Outputs 1.0v1.p2=Point(x=2,y=0)print(v1.weight)# Outputs now 2.0 since p2 changed# NOTE: if we would have written v1.p2.x = 2 instead of v1.p2 = Point(x=2, y=0), it would not have worked, because of the way pydantic triggers validations# The computed field only gets updated if one of the fields in the same model changes (in this case it is property p1 of Vector)