I want to use all subclasses of an abstract class in the nested config class of a pydantic class like this:
def custom_json_loads(classes, ....):
##use classes here for json parsing
class Outer(BaseModel, abc.ABC):
name = "test"
class Config:
json_loads = partial(custom_json_loads, Outer.__subclasses__)
The aim of it all is that I know the OuterClass Type for my JSON and the name of the classes signify which instance of a subclass should be created
E.g. I have BlueOuter, RedOuter, GreenOuter and in the json there would be "outer" : { "name" : "BlueOuter", ....}
But I don't want to import all possible variants of the subclasses because they evolve over time
Why not use a discriminated union?
Output:
If you worry about the need to mantain
OuterUnionwhen a newOutersubclass is added, you could have a unit test to check thatOuterUnionhas all the subclasses ofOuter:Output: