Search code examples
pythonpython-typingpydantic

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


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

Solution

  • 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.