1

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Min-Soo Pipefeet
  • 2,208
  • 4
  • 12
  • 31
  • 1
    @Georgy Thx for the hint. It's close to my case but does not reflect it completely, as in my case `pydantic` is in place and could offer other means to exclude `None`. – Min-Soo Pipefeet Nov 28 '19 at 10:23

1 Answers1

3

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.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
SColvin
  • 11,584
  • 6
  • 57
  • 71