Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to type hint a `pl.date`?

Suppose we create some dates:

import polars as pl

df = pl.DataFrame(
    [
        pl.Series("start", ["2023-01-01"], dtype=pl.Date).str.to_date(),
        pl.Series("end", ["2024-01-01"], dtype=pl.Date).str.to_date(),
    ]
)

Now I can create a date range from these:

dates = pl.date_range(df[0, "start"], df[0, "end"], "1mo", eager=True)

But I want to define a function which takes a couple of dates and spits out a range, as a wrapper around pl.date_range:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def my_date_range(start: pl.Date, end: pl.Date) -> pl.Series:
    return pl.date_range(start, end, "1mo", eager=True)

The above doesn’t typecheck with pyright/Pylance, because:

Argument of type "Date" cannot be assigned to parameter "start" of type "IntoExprColumn | date | datetime" in function "date_range"
  Type "Date" is incompatible with type "IntoExprColumn | date | datetime"
    "Date" is incompatible with "date"
    "Date" is incompatible with "datetime"
    "Date" is incompatible with "Expr"
    "Date" is incompatible with "Series"
    "Date" is incompatible with "str"PylancereportArgumentType

If I check out type(df[0, "start"]), I see:

datetime.date

and pl.Date is no good because isinstance(df[0, "start"], pl.Date) == False.

I cannot figure out how to import datetime.date in order to use it as a type annotation (trying import polars.datetime as dt raises No module named 'polars.datetime').

How can this be done? Or put differently: how should my_date_range‘s date arguments be annotated?

>Solution :

Since datetime.date is compatible with the start and end parameters expected by pl.date_range() this should be sufficient:

import polars as pl
from datetime import date

def my_date_range(start: date, end: date) -> pl.Series:
    return pl.date_range(start, end, "1mo", eager=True)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading