Search code examples
pythonsubclasspydanticpython-dataclasses

How to print sub-class name in pydantic?


I used pydantic to define a class. I created a sub-class inherent from a parent class. When I print sub-class, why does it still show the parent class name? What should I do to print Word class?

class SubWord(BaseModel):
    word: str
    label: str

Word = SubWord

word = [Word(word="apple",label="fruit")]
print(f'word: {word}')

This is the result:

word: [SubWord(word='apple', label='fruit')]

But I am expecting:

word: [Word(word='apple', label='fruit')]

What should I do here? Thanks in advance!


Solution

  • Any class and not just Pydantic's would behave in the same way

    class Asd:
        pass
    
    Lol = Asd
    
    >>> Asd
    __main__.Asd
    >>> Lol
    __main__.Asd
    

    In my example Lol is simply a new variable pointing at Asd, so it's not a new class.

    In your case, if SubWord and Word are identical there is no need for you to separate them. Just use Word if that's the word you want to use in your code.

    If you need to separate them for some good reason, then you can use inheritance to effectively copy and rename

    class Word(SubWord):
        pass