Skip to content

Commit e5baff4

Browse files
refactor: Move Object lit fix earlier in the function (#25713)
Co-authored-by: Orson Peters <orsonpeters@gmail.com>
1 parent ee79be3 commit e5baff4

2 files changed

Lines changed: 15 additions & 9 deletions

File tree

py-polars/src/polars/functions/lit.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,12 @@
1616
)
1717
from polars._dependencies import numpy as np
1818
from polars._utils.wrap import wrap_expr
19-
from polars.datatypes import BaseExtension, Date, Datetime, Duration
19+
from polars.datatypes import BaseExtension, Date, Datetime, Duration, Object
2020
from polars.datatypes.convert import DataTypeMappings
2121

2222
with contextlib.suppress(ImportError): # Module not available when building docs
2323
import polars._plr as plr
2424

25-
2625
if TYPE_CHECKING:
2726
from polars import Expr
2827
from polars._typing import PolarsDataType, TimeUnit
@@ -84,7 +83,11 @@ def lit(
8483
elif isinstance(dtype, type) and issubclass(dtype, BaseExtension):
8584
msg = f"dtype '{dtype}' is a BaseExtension class, it should be an instance"
8685
raise TypeError(msg)
87-
elif isinstance(value, datetime):
86+
elif dtype == Object:
87+
value_s = pl.Series("literal", [value], dtype=dtype)
88+
return wrap_expr(plr.lit(value_s._s, allow_object, is_scalar=True))
89+
90+
if isinstance(value, datetime):
8891
if dtype == Date:
8992
return wrap_expr(plr.lit(value.date(), allow_object=False, is_scalar=True))
9093

@@ -185,11 +188,7 @@ def lit(
185188
return lit(value.value, dtype=dtype)
186189

187190
if dtype:
188-
value_s = (
189-
pl.Series("literal", [value], dtype=dtype)
190-
if dtype.is_object()
191-
else pl.Series("literal", [value]).cast(dtype)
192-
)
191+
value_s = pl.Series("literal", [value]).cast(dtype)
193192
return wrap_expr(plr.lit(value_s._s, allow_object, is_scalar=True))
194193

195194
if _check_for_numpy(value) and isinstance(value, np.generic):

py-polars/tests/unit/functions/test_lit.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import enum
55
import sys
6-
from datetime import date, datetime, timedelta
6+
from datetime import date, datetime, time, timedelta
77
from decimal import Decimal
88
from typing import TYPE_CHECKING, Any
99

@@ -272,3 +272,10 @@ def test_lit_structs(item: Any) -> None:
272272
def test_numpy_lit(value: Any, expected_dtype: PolarsDataType) -> None:
273273
result = pl.select(pl.lit(value)).get_column("literal")
274274
assert result.dtype == expected_dtype
275+
276+
277+
def test_lit_object_type_25713() -> None:
278+
obj = time(hour=1)
279+
out = pl.select(pl.lit(obj, dtype=pl.Object))
280+
expected = pl.DataFrame({"literal": [obj]}, schema={"literal": pl.Object})
281+
assert out.to_dict(as_series=False) == expected.to_dict(as_series=False)

0 commit comments

Comments
 (0)