fix(python): map a Literal with None to a nullable field (#4927)

`pydantic_to_schema` raises on `Literal["a", "b", None]`, a field
pydantic accepts with `None`. [PEP
586](https://peps.python.org/pep-0586/#legal-parameters-for-literal-at-type-check-time)
reads it as `Union[Literal["a", "b"], None]`, the same type as
`Optional[Literal["a", "b"]]`, which #4678 maps to a nullable `utf8`.
The `None` is the optional part, not a second value type, so #4678's
rule that `Literal["a", 1]` raises does not cover it. The Literal branch
counted `NoneType` anyway and raised "All values of a Literal must have
the same type".

Before, on `1157a07`:

```
$ python probe.py
Optional[Literal]: pyarrow.Field<kind: string>
pydantic accepts None: kind=None
Literal[..., None]: TypeError: Converting Pydantic type to Arrow Type: unsupported type typing.Literal['a', 'b', None]. All values of a Literal must have the same type.
```

After, the last line prints `pyarrow.Field<kind: string>`, nullable. No
issue exists for this.

<details><summary>probe.py</summary>

```python
from typing import Literal, Optional
from lancedb.pydantic import LanceModel, pydantic_to_schema

class Opt(LanceModel):
    kind: Optional[Literal["a", "b"]] = None

class Lit(LanceModel):
    kind: Literal["a", "b", None] = None

print("Optional[Literal]:", pydantic_to_schema(Opt).field("kind"))
print("pydantic accepts None:", Lit(kind=None))
try:
    print("Literal[..., None]:", pydantic_to_schema(Lit).field("kind"))
except TypeError as e:
    print("Literal[..., None]: TypeError:", e)
```

</details>

The fix has two halves, and each test fails without one of them.
`_unwrap_optional_annotation` turns `Literal["a", None]` into
`Literal["a"]`, so the field and a list item become nullable. The
Literal branch skips `None` when it collects value types, so
`Optional[Literal["a", None]]` maps too. A mixed `Literal["a", 1, None]`
still raises, and so does a bare `Literal[None]`.

### Verification

```
# Python 3.12, lancedb 0.42.0b9 wheel from pypi.fury.io (the version at 1157a07), its _lancedb.abi3.so in the tree
$ PYTHONPATH=. python -m pytest -q -p no:cacheprovider tests/test_pydantic.py
this branch:                         87 passed
pydantic.py reverted, tests kept:    2 failed, 85 passed   (TypeError: ... must have the same type)
None kept in the value types only:   1 failed, 86 passed
unwrap change reverted only:         2 failed, 85 passed   (status not nullable; the write fails)
$ PYTHONPATH=. python -m pytest -q -p no:cacheprovider tests/test_pydantic.py tests/test_table.py tests/test_db.py
1157a07:      8 failed, 650 passed, 17 skipped
this branch:  8 failed, 652 passed, 17 skipped   # the same 8 in test_table.py (blob, merge, compact, namespace) on both
$ ruff format --check <both files> && ruff check <both files>      # ruff 0.9.9, as CI pins it
2 files already formatted
All checks passed!
# not run: the Rust build, the full suite; pyright's include list leaves out pydantic.py
```

@Xuanwo, you merged #4678. I left a bare `Literal[None]` raising, since
a column that can only hold null has no value type to store. Does that
match how you want it?

---------

Signed-off-by: Christopher Krah <48338417+chrikrah@users.noreply.github.com>
This commit is contained in:
Christopher Krah
2026-11-30 19:16:26 +08:00
committed by GitHub
parent 855bec2a57
commit c0d46c31ba
3 changed files with 87 additions and 1 deletions
+2
View File
@@ -76,6 +76,8 @@ Current supported type conversions:
| `list` | `pyarrow.List` |
| `BaseModel` | `pyarrow.Struct` |
| `Vector(n)` | `pyarrow.FixedSizeList(float32, n)` |
| `Literal["a", "b"]` | the Arrow type of its values, here `pyarrow.utf8()`; every value must have the same type |
| `Literal["a", None]` | the same type, nullable, like `Optional[Literal["a"]]` |
LanceDB supports to create Apache Arrow Schema from a
`pydantic.BaseModel`
+24 -1
View File
@@ -257,7 +257,8 @@ def _py_type_to_arrow_type(py_type: Type[Any], field: FieldInfo) -> pa.DataType:
return pa.duration("us")
elif get_origin(py_type) is Literal:
# Store a Literal as the type of its values, e.g. Literal["a", "b"] as utf8.
value_types = {type(value) for value in get_args(py_type)}
# A None value makes the field nullable and has no type of its own.
value_types = {type(value) for value in _literal_values_without_none(py_type)}
if len(value_types) != 1:
raise TypeError(
"Converting Pydantic type to Arrow Type: unsupported type "
@@ -346,7 +347,29 @@ def _pydantic_list_child_to_arrow(child: Any, field: FieldInfo) -> pa.DataType:
return pa.list_(_pydantic_type_to_arrow_type(child, field))
def _literal_values_without_none(literal: Any) -> tuple:
"""Return the values of a Literal, dropping None, which makes it nullable.
A plain Enum member is stored as its value and does not equal it, so a
nullable Literal of one could not be read back. Its None is kept, and the
Literal is rejected for mixing value types, as it was before None counted
as nullability.
"""
values = get_args(literal)
non_none = tuple(value for value in values if value is not None)
if any(isinstance(v, Enum) and not isinstance(v, type(v.value)) for v in non_none):
return values
return non_none
def _unwrap_optional_annotation(annotation: Any) -> Any | None:
if get_origin(annotation) is Literal:
# Literal["a", None] is the same type as Optional[Literal["a"]] (PEP 586).
values = get_args(annotation)
non_none = _literal_values_without_none(annotation)
if non_none and len(non_none) != len(values):
return Literal[non_none]
return None
if isinstance(annotation, (_GenericAlias, GenericAlias)):
origin = annotation.__origin__
args = annotation.__args__
+61
View File
@@ -1254,6 +1254,67 @@ def test_literal_with_mixed_value_types_raises_type_error(annotation):
pydantic_to_schema(TestModel)
def test_literal_with_none_is_nullable():
# Literal["a", None] is the same type as Optional[Literal["a"]] (PEP 586)
class TestModel(pydantic.BaseModel):
status: Literal["todo", "done", None] = None
opt_status: Optional[Literal["todo", None]] = None
tags: List[Literal["a", "b", None]]
schema = pydantic_to_schema(TestModel)
assert schema.field("status").type == pa.utf8()
assert schema.field("status").nullable
assert schema.field("opt_status").type == pa.utf8()
assert schema.field("opt_status").nullable
assert schema.field("tags").type == pa.list_(pa.field("item", pa.utf8(), True))
def test_literal_with_none_round_trip(mem_db):
class TestModel(LanceModel):
status: Literal["todo", "done", None] = None
vector: Vector(2)
rows = [
TestModel(status="done", vector=[1.0, 2.0]),
TestModel(status=None, vector=[3.0, 4.0]),
]
tbl = mem_db.create_table("test", schema=TestModel)
tbl.add(rows)
assert tbl.search().to_pydantic(TestModel) == rows
def test_literal_of_plain_enum_with_none_raises_type_error():
# The stored value "red" would not validate against Color.RED on read.
class Color(Enum):
RED = "red"
for annotation in (Literal[Color.RED, None], Optional[Literal[Color.RED, None]]):
TestModel = pydantic.create_model("TestModel", color=(annotation, None))
with pytest.raises(TypeError, match="same type"):
pydantic_to_schema(TestModel)
def test_literal_of_str_enum_with_none_round_trip(mem_db):
class Color(str, Enum):
RED = "red"
class TestModel(LanceModel):
color: Literal[Color.RED, None] = None
vector: Vector(2)
rows = [
TestModel(color=Color.RED, vector=[1.0, 2.0]),
TestModel(color=None, vector=[3.0, 4.0]),
]
tbl = mem_db.create_table("test", schema=TestModel)
tbl.add(rows)
assert tbl.search().to_pydantic(TestModel) == rows
def test_literal_time_and_timedelta_round_trip(mem_db):
class TestModel(LanceModel):
status: Literal["todo", "done"]