Which type hint expresses that an attribute must not be None?

不想你离开。 提交于 2021-01-28 06:26:31

问题


In the following code, I need to declare my_attr as anything except None.

What should I exchange Any for?

from pydantic import BaseModel
from typing import Any

class MyClass(BaseModel):
    my_attr: Any

回答1:


To achieve this you would need to use a validator, something like:

from pydantic import BaseModel, validator

class MyClass(BaseModel):
    my_attr: Any

    @validator('my_attr', always=True)
    def check_not_none(cls, value):
        assert value is not None, 'may not be None'
        return value

But it's unlikely this is actually what you want, you'd do better to use a union and include an exhaustive list of types you would allow, e.g. Union[str, bytes, int, float, Decimal, datetime, date, list, dict, ...].

If you just want to make the field required (but with None still an allowed value), it should be possible after v1.2 which should be released in the next few days. see samuelcolvin/pydantic#1031.



来源:https://stackoverflow.com/questions/59073717/which-type-hint-expresses-that-an-attribute-must-not-be-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!