哪种类型提示表示属性不能为 None? [英] Which type hint expresses that an attribute must not be None?

查看:27
本文介绍了哪种类型提示表示属性不能为 None?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我需要将 my_attr 声明为任何except None.

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

我应该用Any换什么?

from pydantic import BaseModel
from typing import Any

class MyClass(BaseModel):
    my_attr: Any

推荐答案

要实现这一点,您需要使用验证器,例如:

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

但这实际上不太可能是您想要的,您最好使用联合并包含您允许的详尽类型列表,例如Union[str, bytes, int, float, Decimal, datetime, date, list, dict, ...].

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, ...].

如果你只是想让这个字段成为必需的(但 None 仍然是一个允许的值),在 v1.2 之后应该是可能的,它应该在接下来的几天内发布.请参阅 samuelcolvin/pydantic#1031.

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.

这篇关于哪种类型提示表示属性不能为 None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆