Pydantic - Dynamically create a model with multiple base classes?

2024/10/6 22:08:21

From the pydantic docs I understand this:

import pydanticclass User(pydantic.BaseModel):id: intname: strclass Student(pydantic.BaseModel):semester: int# this works as expected
class Student_User(User, Student):building: strprint(Student_User.__fields__.keys())
#> dict_keys(['semester', 'id', 'name', 'building'])

However, when I want to create a similar object dynamically (following the section dynamic-model-creation):

# this results in a TypeError
pydantic.create_model("Student_User2", __base__=(User, Student))

I get:

TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

Question: How to dynamically create a class like Student_User

Answer

Its not the answer to the original question, but if you are like me and all you care about is having a model which holds fields of other models, this should be a solutions.

Student_User = pydantic.create_model("Student_User", **{**{key: (value.type_, value.default) for key, value in User.__fields__.items()},**{key: (value.type_, value.default) for key, value in Student.__fields__.items()},**{"building": (str, '')},
})

Essentially, we are dynamically creating a new pydantic model and we are setting its fields to be the fields of our other models plus an additional custom field.

Note: OP included these lines in his question:

print(Student_User.__fields__.keys())
#> dict_keys(['semester', 'id', 'name', 'building'])

So, my guess is that his end goal was copying the fields from the other models and having a model created from multiple bases was just a method of achieving it.

https://en.xdnf.cn/q/73180.html

Related Q&A

Handling nested elements with Python lxml

Given the simple XML data below:<book><title>My First Book</title><abstract><para>First paragraph of the abstract</para><para>Second paragraph of the abstract&…

Easiest way to plot data on country map with python

Could not delete question. Please refer to question: Shade states of a country according to dictionary values with Basemap I want to plot data (number of sick people for a certain year) on each state o…

How to resize QMainWindow after removing all DockWidgets?

I’m trying to make an application consisting of a QMainWindow, the central widget of which is a QToolBar (it may not be usual, but for my purpose the toolbar’s well suited). Docks are allowed below o…

Python: sorting a list by column [duplicate]

This question already has answers here:How to sort a list/tuple of lists/tuples by the element at a given index(11 answers)Closed 8 years ago.How can I sort a list-of-lists by "column", i.e. …

How to make setuptools clone git dependencies recursively?

I want to let setuptools install Phoenix in my project and thus addedsetup(...dependency_links = ["git+https://github.com/wxWidgets/Phoenix.git#egg=Phoenix"],install_requires = ["Phoenix…

Stable sorting in Jinja2

It is possible to apply the sort filter in Jinja2 successively to sort a list first by one attribute, then by another? This seems like a natural thing to do, but in my testing, the preceeding sort is …

Factor to complex roots using sympy

I cant figure out how to factor an polynomial expression to its complex roots.>>> from sympy import * >>> s = symbol(s) >>> factor(s**2+1)2 s + 1

Using multiple custom classes with Pipeline sklearn (Python)

I try to do a tutorial on Pipeline for students but I block. Im not an expert but Im trying to improve. So thank you for your indulgence. In fact, I try in a pipeline to execute several steps in prepar…

Python equivalent of pointers

In python everything works by reference:>>> a = 1 >>> d = {a:a} >>> d[a] 1 >>> a = 2 >>> d[a] 1I want something like this>>> a = 1 >>> d =…

Pip is broken, gives PermissionError: [WinError 32]

I installed the python-certifi-win32 module (Im so busy trying to fix this problem that I dont even remember why I originally installed it). Right after I installed it, though, I started getting this e…