Search code examples
pythonooppydantic

Short way to get all field names of a pydantic class


Minimal example of the class:

from pydantic import BaseModel

class AdaptedModel(BaseModel):
    def get_all_fields(self, alias=False):
        return list(self.schema(by_alias=alias).get("properties").keys())

class TestClass(AdaptedModel):
    test: str

The way it works:

dm.TestClass.get_all_fields(dm.TestClass)

Is there a way to make it work without giving the class again?

Desired way to get all field names:

dm.TestClass.get_all_fields()

It would also work if the field names are assigned to an attribute. Just any way to make it make it more readable


Solution

  • What about just using __fields__:

    from pydantic import BaseModel
    
    class AdaptedModel(BaseModel):
        parent_attr: str
    
    class TestClass(AdaptedModel):
        child_attr: str
            
    TestClass.__fields__
    

    Output:

    {'parent_attr': ModelField(name='parent_attr', type=str, required=True),
     'child_attr': ModelField(name='child_attr', type=str, required=True)}
    

    This is just a dict and you could get only the field names simply by: TestClass.__fields__.keys()

    See model properties: https://pydantic-docs.helpmanual.io/usage/models/#model-properties