I want to be able to create a python class like the following programmatically:
class Foo(BaseModel):
bar: str = "baz"
The following almost works:
Foo = type("Foo", (BaseModel,), {"bar":"baz"})
But doesn't include the annotation, Foo.__annotations__
is set in first example but not the second.
Is there any way to achieve this?
My motivation is to create a class decorator that creates a clone of the decorated class with modified type annotations. The annotations have to be set during class creation (not after the fact) to that the metaclass of BaseModel will see them.
data = {"bar":"baz"}
data["__annotations__"]={key:type(value) for key,value in data.items()}
y = type("Foo", (BaseModel,), data)
– Outandout