You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优雅列出Pydantic BaseModel中定义的所有属性?

如何优雅列出Pydantic BaseModel中的@property属性

Pydantic 提供了model_fields获取普通字段、model_computed_fields获取计算字段,但确实没有直接的API提取用@property装饰的属性。这里有两种实用方法可以实现需求:

方法一:用inspect模块筛选类成员

通过inspect.getmembers遍历类的所有成员,判断是否为property类型,就能精准筛选出所有@property属性:

import inspect
from pydantic import BaseModel

class Test(BaseModel):
    field: str

    @property
    def len_field(self) -> int:
        return len(self.field)
    
    @property
    def first_char(self) -> str:
        return self.field[0]

def get_property_names(model_cls):
    return [name for name, member in inspect.getmembers(model_cls) if isinstance(member, property)]

# 调用示例
print(get_property_names(Test))  # 输出: ['len_field', 'first_char']

方法二:合并所有类型的字段/属性

如果需要一次性获取普通字段、计算字段和@property属性,可以把三者结果合并:

def get_all_fields_and_properties(model_cls):
    regular_fields = list(model_cls.model_fields.keys())
    computed_fields = list(model_cls.model_computed_fields.keys())
    properties = get_property_names(model_cls)
    return regular_fields + computed_fields + properties

# 调用示例
print(get_all_fields_and_properties(Test))  # 输出: ['field', 'len_field', 'first_char']

注意:如果从实例的dir()结果里筛选,需要额外排除Pydantic自带的大量内置属性(比如model_config、model_dump这类),相比之下用inspect直接操作类的方法更简洁可靠。

内容的提问来源于stack exchange,提问作者SultanOrazbayev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 15:50:01