How to set a Pydantic field value depending on other fields

2024/10/5 14:26:05
from pydantic import BaseModelclass Grafana(BaseModel):user: strpassword: strhost: strport: strapi_key: str | None = NoneGRAFANA_URL = f"http://{user}:{password}@{host}:{port}"API_DATASOURCES = "/api/datasources"API_KEYS = "/api/auth/keys"

With Pydantic I get two unbound variables error messages for user, password, etc. in GRAFANA_URL.

Is there a way to solve this? In a regular class, I would just create GRAFANA_URL in the __init__ method. With Pydantic, I'm not sure how to proceed.

Answer

Option A: Use a @validator

See the validators documentation for details.

from typing import Anyfrom pydantic import BaseModel, validatorclass Model(BaseModel):foo: strbar: strfoobar: str = ""@validator("foobar", always=True)def set_if_empty(cls, v: str, values: dict[str, Any]) -> str:if v == "":return values["foo"] + values["bar"]return vobj = Model(foo="a", bar="b")
print(obj)  # foo='a' bar='b' foobar='ab'

That way foobar remains a regular model field.

Note that for this to work, foobar must be defined after foo and bar. Otherwise you will have to use a root validator.

Option B: Make it a @property

from pydantic import BaseModelclass Model(BaseModel):foo: strbar: str@propertydef foobar(self) -> str:return self.foo + self.barobj = Model(foo="a", bar="b")
print(obj)         # foo='a' bar='b'
print(obj.foobar)  # ab

Then foobar will not be a model field anymore and therefore not part of the schema. That may or may not be relevant to you.

Option C: Make it a @computed_field (Pydantic v2 only!)

Defining computed fields will be available for Pydantic 2.

from pydantic import BaseModel, computed_fieldclass Model(BaseModel):foo: strbar: str@computed_field@propertydef foobar(self) -> str:return self.foo + self.barobj = Model(foo="a", bar="b")
print(obj)         # foo='a' bar='b' foobar='ab'
https://en.xdnf.cn/q/73339.html

Related Q&A

Cascade multiple RNN models for N-dimensional output

Im having some difficulty with chaining together two models in an unusual way. I am trying to replicate the following flowchart:For clarity, at each timestep of Model[0] I am attempting to generate an …

Pandas Flatten a list of list within a column?

I am trying to flatten a column which is a list of lists:var var2 0 9122532.0 [[458182615.0], [79834910.0]] 1 79834910.0 [[458182615.0], [9122532.0]] 2 458182615.0 [[79834910.0], [9122…

How to use libxml2 with python on macOs?

Im on OSX Lion and I have libxml2 installed (by default) and I have python installed (by default) but they dont talk to one another. Whats the simplest way to make this work on Lion?$ python -c "…

SMTP Authentication error while while sending mail from outlook using python language

import smtplibsmtpObj = smtplib.SMTP(smtp.office365.com, 587)smtpObj.ehlo()smtpObj.starttls()smtpObj.login([email protected], abcde)smtpObj.sendmail([email protected], [email protected], Subject: So l…

How do you change environment of Python Interactive on Vscode?

I recently migrated from Spyder to VScode. I created a new conda environment and used setting.json to change the environment in VScode, "python.pythonPath": "/Users/dcai/anaconda3/envs/…

Validate list in marshmallow

currently I am using marshmallow schema to validate the request, and I have this a list and I need to validate the content of it.class PostValidationSchema(Schema):checks = fields.List(fields.String(re…

Save unicode in redis but fetch error

Im using mongodb and redis, redis is my cache.Im caching mongodb objects with redis-py:obj in mongodb: {uname: umatch, usection_title: u\u6d3b\u52a8, utitle: u\u6bd4\u8d5b, usection_id: 1, u_id: Objec…

Authentication with public keys and cx_Oracle using Python

Ive Googled a bit but I havent found any substantial results. Is it possible to use key-based authentication to connect to an Oracle server using Python? My objective is to be able to automate some re…

No luck pip-installing pylint for Python 3

Im interested in running a checker over my Python 3 code to point out possible flaws. PyChecker does not work with Python 3. I tried to pip-install Pylint, but this fails. The error message does not he…

How to use tf.nn.embedding_lookup_sparse in TensorFlow?

We have tried using tf.nn.embedding_lookup and it works. But it needs dense input data and now we need tf.nn.embedding_lookup_sparse for sparse input.I have written the following code but get some erro…