Skip to content

Commit

Permalink
lint
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoGorelli committed May 30, 2024
1 parent 294dbaa commit 37a9ea0
Show file tree
Hide file tree
Showing 17 changed files with 106 additions and 78 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ install-release: venv

pre-commit: venv
cargo fmt --all && cargo clippy --all-features
.venv/bin/python -m ruff check . --fix --exit-non-zero-on-fix
.venv/bin/python -m ruff check polars_xdt tests --fix --exit-non-zero-on-fix
.venv/bin/python -m ruff format polars_xdt tests
.venv/bin/python -m mypy polars_xdt tests

Expand Down
20 changes: 16 additions & 4 deletions polars_xdt/functions.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from __future__ import annotations
import warnings

import re
import sys
import warnings
from datetime import date, timedelta
from pathlib import Path
from typing import TYPE_CHECKING, Literal, Sequence
Expand Down Expand Up @@ -158,7 +158,11 @@ def offset_by(
└────────────┴──────┴──────────────┘
"""
warnings.warn("`offset_by` is deprecated, as it has been upstreamed. Please use `polars.add_business_days` instead.", DeprecationWarning, stacklevel=2)
warnings.warn(
"`offset_by` is deprecated, as it has been upstreamed. Please use `polars.add_business_days` instead.",
DeprecationWarning,
stacklevel=2,
)
expr = parse_into_expr(expr)
if (
isinstance(by, str)
Expand Down Expand Up @@ -727,7 +731,11 @@ def workday_count(
└────────────┴────────────┴─────────────────┘
"""
warnings.warn("`workday_count` is deprecated, as it has been upstreamed. Please use `polars.business_day_count` instead.", DeprecationWarning, stacklevel=2)
warnings.warn(
"`workday_count` is deprecated, as it has been upstreamed. Please use `polars.business_day_count` instead.",
DeprecationWarning,
stacklevel=2,
)
start_dates = parse_into_expr(start_dates)
end_dates = parse_into_expr(end_dates)
weekmask = get_weekmask(weekend)
Expand Down Expand Up @@ -991,7 +999,11 @@ def ewma_by_time(
└────────┴────────────┴──────────┘
"""
warnings.warn("`ewma_by_time` is deprecated, as it has been upstreamed. Please use `polars.ewm_mean_by` instead.", DeprecationWarning, stacklevel=2)
warnings.warn(
"`ewma_by_time` is deprecated, as it has been upstreamed. Please use `polars.ewm_mean_by` instead.",
DeprecationWarning,
stacklevel=2,
)
values = parse_into_expr(values)
half_life_us = (
int(half_life.total_seconds()) * 1_000_000 + half_life.microseconds
Expand Down
9 changes: 3 additions & 6 deletions polars_xdt/ranges.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ def date_range(
eager: Literal[False] = ...,
weekend: Sequence[str] = ...,
holidays: Sequence[date] | None = ...,
) -> pl.Expr:
...
) -> pl.Expr: ...


@overload
Expand All @@ -41,8 +40,7 @@ def date_range(
eager: Literal[True],
weekend: Sequence[str] = ...,
holidays: Sequence[date] | None = ...,
) -> pl.Series:
...
) -> pl.Series: ...


@overload
Expand All @@ -57,8 +55,7 @@ def date_range(
eager: bool = ...,
weekend: Sequence[str] = ...,
holidays: Sequence[date] | None = ...,
) -> pl.Series | pl.Expr:
...
) -> pl.Series | pl.Expr: ...


def date_range( # noqa: PLR0913
Expand Down
10 changes: 6 additions & 4 deletions src/business_days.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,10 +191,12 @@ pub(crate) fn impl_advance_n_days(
ca.try_apply_nonnull_values_generic(|x| {
let x_date = (x / multiplier) as i32;
let x_weekday = weekday(x_date);
Ok::<i64, PolarsError>(x + ((calculate_advance(
x_date, n, x_weekday, weekmask, n_weekdays, &holidays, roll,
)? - x_date) as i64
* multiplier))
Ok::<i64, PolarsError>(
x + ((calculate_advance(
x_date, n, x_weekday, weekmask, n_weekdays, &holidays, roll,
)? - x_date) as i64
* multiplier),
)
})
} else {
Ok(Int64Chunked::full_null(ca.name(), ca.len()))
Expand Down
6 changes: 3 additions & 3 deletions src/ewma_by_time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pub(crate) fn impl_ewma_by_time_float(
times: &Int64Chunked,
values: &Float64Chunked,
half_life: i64,
time_unit: TimeUnit
time_unit: TimeUnit,
) -> Float64Chunked {
let mut out = Vec::with_capacity(times.len());
if values.is_empty() {
Expand All @@ -29,7 +29,7 @@ pub(crate) fn impl_ewma_by_time_float(
out.push(Some(prev_result));
skip_rows = idx + 1;
break;
},
}
_ => {
out.push(None);
}
Expand All @@ -50,7 +50,7 @@ pub(crate) fn impl_ewma_by_time_float(
prev_time = time;
prev_result = result;
out.push(Some(result));
},
}
_ => out.push(None),
}
});
Expand Down
2 changes: 1 addition & 1 deletion src/expressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ fn arg_previous_greater(inputs: &[Series]) -> PolarsResult<Series> {

#[derive(Deserialize)]
struct EwmTimeKwargs {
half_life: i64
half_life: i64,
}

#[polars_expr(output_type=Float64)]
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ mod to_julian;
mod utc_offsets;

use pyo3::types::PyModule;
use pyo3::{pymodule, PyResult, Bound};
use pyo3::{pymodule, Bound, PyResult};

#[cfg(target_os = "linux")]
use jemallocator::Jemalloc;
Expand Down
2 changes: 1 addition & 1 deletion src/timezone.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use arity::try_binary_elementwise;
use chrono::{LocalResult, NaiveDateTime, TimeZone};
use polars_arrow::legacy::time_zone::Tz;
use polars::chunked_array::temporal::parse_time_zone;
use polars::prelude::*;
use polars_arrow::legacy::time_zone::Tz;
use pyo3_polars::export::polars_core::utils::arrow::legacy::kernels::Ambiguous;
use pyo3_polars::export::polars_core::utils::arrow::temporal_conversions::{
timestamp_ms_to_datetime, timestamp_ns_to_datetime, timestamp_us_to_datetime,
Expand Down
2 changes: 2 additions & 0 deletions tests/ceil_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from datetime import datetime

import polars as pl

import polars_xdt as xdt


Expand Down
5 changes: 3 additions & 2 deletions tests/julian_date_test.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from __future__ import annotations

import datetime as dt

import hypothesis.strategies as st
import pandas as pd
import polars as pl
from hypothesis import given

import polars as pl
import pandas as pd
import polars_xdt as xdt


Expand Down
55 changes: 27 additions & 28 deletions tests/test_business_offsets.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
from __future__ import annotations

import datetime as dt
from polars.testing import assert_frame_equal
import pytest
from typing import Mapping, Any, Callable, Literal
from typing import TYPE_CHECKING, Any, Callable, Literal

import hypothesis.strategies as st
import numpy as np
from hypothesis import given, assume, reject

import polars as pl
import pytest
from hypothesis import assume, given, reject
from polars.testing import assert_frame_equal

import polars_xdt as xdt
from polars.type_aliases import PolarsDataType

if TYPE_CHECKING:
from polars.type_aliases import PolarsDataType

mapping = {"Mon": 1, "Tue": 2, "Wed": 3, "Thu": 4, "Fri": 5, "Sat": 6, "Sun": 7}
reverse_mapping = {value: key for key, value in mapping.items()}
Expand Down Expand Up @@ -47,8 +48,8 @@ def get_result(
)["ts"]
.item()
)
except Exception as exp:
assert "non-existent" in str(exp) or "ambiguous" in str(exp)
except Exception as exp: # noqa: BLE001
assert "non-existent" in str(exp) or "ambiguous" in str(exp) # noqa: PT017
reject()
return result # type: ignore[no-any-return]

Expand Down Expand Up @@ -81,7 +82,7 @@ def get_result(
),
function=st.sampled_from([lambda x: x, lambda x: pl.Series([x])]),
)
def test_against_np_busday_offset(
def test_against_np_busday_offset( # noqa: PLR0913
date: dt.date,
n: int,
weekend: list[str],
Expand Down Expand Up @@ -135,7 +136,7 @@ def test_against_np_busday_offset(
function=st.sampled_from([lambda x: x, lambda x: pl.Series([x])]),
roll=st.sampled_from(["forward", "backward"]),
)
def test_against_np_busday_offset_with_roll(
def test_against_np_busday_offset_with_roll( # noqa:PLR0913
date: dt.date,
n: int,
weekend: list[str],
Expand Down Expand Up @@ -205,29 +206,27 @@ def test_starting_on_non_business() -> None:
n = -7
weekend = ["Sat", "Sun"]
df = pl.DataFrame({"dates": [start]})
with pytest.raises(pl.ComputeError):
with pytest.deprecated_call():
df.with_columns(
dates_shifted=xdt.offset_by(
"dates",
by=f"{n}bd",
weekend=weekend,
)
with pytest.raises(pl.ComputeError), pytest.deprecated_call():
df.with_columns(
dates_shifted=xdt.offset_by(
"dates",
by=f"{n}bd",
weekend=weekend,
)
)

df = pl.DataFrame({"dates": [start]})
weekend = []
holidays = [start]
with pytest.raises(pl.ComputeError):
with pytest.deprecated_call():
df.with_columns(
dates_shifted=xdt.offset_by(
"dates",
by=f"{n}bd",
holidays=holidays,
weekend=weekend,
)
with pytest.raises(pl.ComputeError), pytest.deprecated_call():
df.with_columns(
dates_shifted=xdt.offset_by(
"dates",
by=f"{n}bd",
holidays=holidays,
weekend=weekend,
)
)


def test_within_group_by() -> None:
Expand Down Expand Up @@ -262,6 +261,6 @@ def test_invalid_roll_strategy() -> None:
)
}
)
with pytest.raises(pl.ComputeError):
with pytest.raises(pl.ComputeError): # noqa: SIM117
with pytest.deprecated_call():
df.with_columns(xdt.offset_by("date", "1bd", roll="cabbage")) # type: ignore[arg-type]
7 changes: 5 additions & 2 deletions tests/test_date_range.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from __future__ import annotations

from datetime import date

import polars as pl
import pytest
from datetime import date
import polars_xdt as xdt # noqa: F401
from polars.testing import assert_series_equal

import polars_xdt as xdt


def test_eager() -> None:
result = xdt.date_range(date(2023, 1, 1), date(2023, 1, 10), eager=True)
Expand Down
28 changes: 17 additions & 11 deletions tests/test_ewma_by_time.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,29 @@
import os
from datetime import datetime, timedelta

import polars as pl
from polars.testing import assert_frame_equal
import polars_xdt as xdt
import pytest
from datetime import datetime, timedelta
from polars.testing import assert_frame_equal

import os
import polars_xdt as xdt

os.environ["POLARS_VERBOSE"] = "1"


@pytest.mark.parametrize("start_null", [True, False])
def test_ewma_by_time(start_null):
def test_ewma_by_time(*, start_null: bool) -> None:
if start_null:
values = [None]
times = [datetime(2020, 1, 1)]
else:
values = []
times = []

df = pl.DataFrame(
{
"values": values + [0.0, 1., 2., None, 4.],
"times": times + [
"values": [*values, 0.0, 1.0, 2.0, None, 4.0],
"times": [
*times,
datetime(2020, 1, 2),
datetime(2020, 1, 4),
datetime(2020, 1, 11),
Expand All @@ -31,12 +34,15 @@ def test_ewma_by_time(start_null):
)
with pytest.deprecated_call():
result = df.select(
xdt.ewma_by_time("values", times="times", half_life=timedelta(days=2)),
xdt.ewma_by_time(
"values", times="times", half_life=timedelta(days=2)
),
)

expected = pl.DataFrame(
{
"values": values + [
"values": [
*values,
0.0,
0.5,
1.8674174785275222,
Expand Down
6 changes: 3 additions & 3 deletions tests/test_format_localized.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import pytest

from datetime import datetime, date
from datetime import date, datetime

import polars as pl
import pytest
from polars.type_aliases import TimeUnit

import polars_xdt as xdt


Expand Down
4 changes: 2 additions & 2 deletions tests/test_is_busday.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
from __future__ import annotations

import datetime as dt

import hypothesis.strategies as st
import numpy as np
import polars as pl
from hypothesis import given

import polars as pl
import polars_xdt as xdt


mapping = {"Mon": 1, "Tue": 2, "Wed": 3, "Thu": 4, "Fri": 5, "Sat": 6, "Sun": 7}
reverse_mapping = {value: key for key, value in mapping.items()}

Expand Down
Loading

0 comments on commit 37a9ea0

Please sign in to comment.