【问题标题】:How can pydantic validator access 2nd attribute?pydantic 验证器如何访问第二个属性?
【发布时间】:2021-12-30 10:46:41
【问题描述】:

pydantic 验证器如何访问类属性(要验证的属性除外)。

我知道如何通过关键字传递另一个值。如何访问位于类内的属性?类似于其他类函数的self.xx 语句。

这是我正在尝试的,它失败了:

from pydantic import BaseModel, validator
from typing import TypeVar, Dict, Optional
PandasDataFrame = TypeVar('pandas.core.frame.DataFrame')

class GameResults(BaseModel):  
    game_results_cols: Dict[str, str] = {'League': 'object',
                                         'Season': 'int64',
                                         'Home team goals': 'int64',
                                         'Guest team goals': 'int64'}
    game_results: Optional[PandasDataFrame]
    
    @validator("game_results")
    def game_results_has_right_dtypes(cls, v) -> PandasDataFrame:
        # Check that all columns are in fact of the dtype that they should be, according to the game_results_cols dict
        if v is not None:
            for check_type in ['int64', 'object', 'datetime64[ns]']:
                for c in [c for c in v.columns if cls.game_results_cols[c] == check_type]:
                    if v[c].dtypes != check_type:
                        raise TypeError(f"{c} is of dtype {v[c].dtypes}, but should be of type {check_type}.")
        return v
    

以上代码在创建实例时失败

import pandas as pd
my_game = GameResults(game_results = pd.DataFrame(['Premier League', 2021, 3, 5]))

>> AttributeError: type object 'GameResults' has no attribute 'game_results_cols'

我很困惑..为什么它会失败/我该如何让它工作?我确信该属性本身确实存在,即,当删除验证器时,该属性就在那里,见下文。我什至可以在课堂上print() 它,它会显示出来。验证器无法使用它..?

class GameResults(BaseModel):  
    game_results_cols: Dict[str, str] = {'League': 'object',
                                         'Season': 'int64',
                                         'Home team goals': 'int64',
                                         'Guest team goals': 'int64'}
    game_results: Optional[PandasDataFrame]

my_game = GameResults(game_results = pd.DataFrame(['Premier League', 2021, 3, 5]))
print(my_game.game_results_cols)

>> {'League': 'object', 'Season': 'int64', 'Home team goals': 'int64', 'Guest team goals': 'int64'}

【问题讨论】:

    标签: python validation pydantic


    【解决方案1】:

    您可以通过向验证器支付另一个参数values 来访问其他值,请参阅passwords_match 验证器here

    【讨论】:

    • 不确定,您能举个例子吗?我的问题是 not 我想传递一个额外的关键字,但使用类中的现有属性 (self.xx) 我知道这个例子,但它显示的恰恰相反:在例子中, 'password1' 被显式传递以使用passwords_match 验证'password2'。这不是我需要的
    猜你喜欢
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    相关资源
    最近更新 更多