Runtime type checking using parameterized types

In fact, you could even go one step further and just make it a union if you want to allow B(x=1)

class B(BaseModel):
    x: int | str

B.model_validate({"x": 1})   # ok
B.model_validate({"x": "1"}) # ok
B(x=1)   # ok
B(x="1")   # ok
x=1
x='1'
x=1
x='1'

It all depends what you’re trying to achieve really, and I think pydantic covers probably almost all use cases.

I don’t think you got my point. Look at how the “template” argument (i.e. [int] and [str]) affects the behavior of class instantiation.

I changed my reply. But maybe I don’t understand the problem you’re trying to solve.

The problem with the examples you gave (suppose I understood it correctly) is that you need to hard-code types into your class declaration. Whatever supplied later during instantiation will not be actually used for type check.

I see that your code will work perfect with static linters, but the types you specified in the square brackets does not affect run-time behavior.