Skip to content
Advertisement

Short way to get all field names of a pydantic class

Minimal example of the class:

JavaScript

The way it works:

JavaScript

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

Desired way to get all field names:

JavaScript

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

Advertisement

Answer

What about just using __fields__:

JavaScript

Output:

JavaScript

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

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement