I encountered this while working on #2017:
from typing import List
from pydantic import BaseModel, Json
class JsonDemo(BaseModel):
# I'd expect this to work like typing.List[None], but at definition-time it raises
# RuntimeError: error checking inheritance of None (type: NoneType)
none: Json[None]
JsonDemo(none="null")
class JsonWorkaround(BaseModel):
# The workaround of using type(None) also fails at definition-time, raising
# RuntimeError: no validator found for <class 'NoneType'>, see `arbitrary_types_allowed` in Config
# The same error is apparent for List[None], so I think it's a more general bug
json_null: Json[type(None)]
list_of_none: List[None]
I would expect both Json[None] and List[None] to work, accepting in respectively "null" or a list (or sequence) where all the elements are None - casting need not be supported because None is a singleton.
I think we could have a NoneType which enforces a value to be None. But I think if we made foo: None a valid way of enforcing a value is None it would make a lot of logic more complicated and result in lots of easy traps for people to fall into.
I agree that we should not allow foo: None as a type constraint, but we could allow foo: type(None) or foo: pydantic.typing.NoneType. This would be effectively equivalent to Literal[None].
Mypy, along with other type checkers, already treat foo: None as equivalent to foo: Literal[None] or foo: NoneType. My proposal is that Pydantic match this behaviour, even though it would require some extra logic for the sake of consistency with the rest of the ecosystem.
foo: type(None) makes Mypy fail with error: Invalid type comment or annotation. Suggestion: use type[...] instead of type(...), so while Pydantic should probably allow it at runtime we'd have to recommend assigning type(None) to a variable and using that in annotations.
According to https://www.python.org/dev/peps/pep-0484/#using-none, None should be considered equivalent to type(None), so this is definitely a bug.
@Zac-HD @pxeger I just opened a PR as I agree with both of you.
Feedback more than welcome! :)
Most helpful comment
@Zac-HD @pxeger I just opened a PR as I agree with both of you.
Feedback more than welcome! :)