Skip to content

Commit

Permalink
Modern style type hints (#3863)
Browse files Browse the repository at this point in the history
  • Loading branch information
stinodego committed Jul 4, 2022
1 parent 284e308 commit 98e321d
Show file tree
Hide file tree
Showing 20 changed files with 1,449 additions and 1,599 deletions.
22 changes: 12 additions & 10 deletions py-polars/polars/_html.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,21 @@
"""
Module for formatting output data in HTML.
"""
from __future__ import annotations

from textwrap import dedent
from types import TracebackType
from typing import Dict, Iterable, List, Optional, Type
from typing import Iterable

from polars.datatypes import Object


class Tag:
def __init__(
self,
elements: List[str],
elements: list[str],
tag: str,
attributes: Optional[Dict[str, str]] = None,
attributes: dict[str, str] | None = None,
):
self.tag = tag
self.elements = elements
Expand All @@ -31,17 +33,17 @@ def __enter__(self) -> None:

def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
self.elements.append(f"</{self.tag}>")


class HTMLFormatter:
def __init__(self, df: "DataFrame", max_cols: int = 75, max_rows: int = 40): # type: ignore # noqa
def __init__(self, df: DataFrame, max_cols: int = 75, max_rows: int = 40): # type: ignore # noqa
self.df = df
self.elements: List[str] = []
self.elements: list[str] = []
self.max_cols = max_cols
self.max_rows = max_rows
self.row_idx: Iterable[int]
Expand Down Expand Up @@ -109,7 +111,7 @@ def write_body(self) -> None:
def write(self, inner: str) -> None:
self.elements.append(inner)

def render(self) -> List[str]:
def render(self) -> list[str]:
with Tag(self.elements, "table", {"border": "1", "class": "dataframe"}):
self.write_header()
self.write_body()
Expand Down Expand Up @@ -150,7 +152,7 @@ def write_style(self) -> None:
template = dedent("\n".join((template_first, template_mid, template_last)))
self.write(template)

def render(self) -> List[str]:
def render(self) -> list[str]:
"""
Return the lines needed to render a HTML table.
"""
Expand Down
17 changes: 9 additions & 8 deletions py-polars/polars/cfg.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import os
from typing import Type

from polars.string_cache import toggle_string_cache

Expand All @@ -10,7 +11,7 @@ class Config:
"""

@classmethod
def set_utf8_tables(cls) -> "Type[Config]":
def set_utf8_tables(cls) -> type[Config]:
"""
Use utf8 characters to print tables
"""
Expand All @@ -21,15 +22,15 @@ def set_utf8_tables(cls) -> "Type[Config]":
return cls

@classmethod
def set_ascii_tables(cls) -> "Type[Config]":
def set_ascii_tables(cls) -> type[Config]:
"""
Use ascii characters to print tables
"""
os.environ["POLARS_FMT_NO_UTF8"] = "1"
return cls

@classmethod
def set_tbl_width_chars(cls, width: int) -> "Type[Config]":
def set_tbl_width_chars(cls, width: int) -> type[Config]:
"""
Set the number of character used to draw the table
Expand All @@ -42,7 +43,7 @@ def set_tbl_width_chars(cls, width: int) -> "Type[Config]":
return cls

@classmethod
def set_tbl_rows(cls, n: int) -> "Type[Config]":
def set_tbl_rows(cls, n: int) -> type[Config]:
"""
Set the number of rows used to print tables
Expand All @@ -56,7 +57,7 @@ def set_tbl_rows(cls, n: int) -> "Type[Config]":
return cls

@classmethod
def set_tbl_cols(cls, n: int) -> "Type[Config]":
def set_tbl_cols(cls, n: int) -> type[Config]:
"""
Set the number of columns used to print tables
Expand Down Expand Up @@ -85,15 +86,15 @@ def set_tbl_cols(cls, n: int) -> "Type[Config]":
return cls

@classmethod
def set_global_string_cache(cls) -> "Type[Config]":
def set_global_string_cache(cls) -> type[Config]:
"""
Turn on the global string cache
"""
toggle_string_cache(True)
return cls

@classmethod
def unset_global_string_cache(cls) -> "Type[Config]":
def unset_global_string_cache(cls) -> type[Config]:
"""
Turn off the global string cache
"""
Expand Down
39 changes: 16 additions & 23 deletions py-polars/polars/convert.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
from typing import (
TYPE_CHECKING,
Any,
Dict,
Mapping,
Optional,
Sequence,
Union,
overload,
)
from __future__ import annotations

from typing import TYPE_CHECKING, Any, Mapping, Sequence, overload

import numpy as np

Expand All @@ -28,8 +21,8 @@


def from_dict(
data: Mapping[str, Union[Sequence, Mapping]],
columns: Optional[Sequence[str]] = None,
data: Mapping[str, Sequence | Mapping],
columns: Sequence[str] | None = None,
) -> DataFrame:
"""
Construct a DataFrame from a dictionary of sequences.
Expand Down Expand Up @@ -69,9 +62,9 @@ def from_dict(


def from_records(
data: Union[np.ndarray, Sequence[Sequence[Any]]],
columns: Optional[Sequence[str]] = None,
orient: Optional[str] = None,
data: np.ndarray | Sequence[Sequence[Any]],
columns: Sequence[str] | None = None,
orient: str | None = None,
) -> DataFrame:
"""
Construct a DataFrame from a numpy ndarray or sequence of sequences.
Expand Down Expand Up @@ -118,8 +111,8 @@ def from_records(


def from_dicts(
dicts: Sequence[Dict[str, Any]],
infer_schema_length: Optional[int] = 50,
dicts: Sequence[dict[str, Any]],
infer_schema_length: int | None = 50,
) -> DataFrame:
"""
Construct a DataFrame from a sequence of dictionaries.
Expand Down Expand Up @@ -161,8 +154,8 @@ def from_dicts(

# Note that we cannot overload because pyarrow has no stubs :(
def from_arrow(
a: Union["pa.Table", "pa.Array", "pa.ChunkedArray"], rechunk: bool = True
) -> Union[DataFrame, Series]:
a: pa.Table | pa.Array | pa.ChunkedArray, rechunk: bool = True
) -> DataFrame | Series:
"""
Create a DataFrame or Series from an Arrow Table or Array.
Expand Down Expand Up @@ -230,7 +223,7 @@ def from_arrow(

@overload
def from_pandas(
df: "pd.DataFrame",
df: pd.DataFrame,
rechunk: bool = True,
nan_to_none: bool = True,
) -> DataFrame:
Expand All @@ -239,18 +232,18 @@ def from_pandas(

@overload
def from_pandas(
df: Union["pd.Series", "pd.DatetimeIndex"],
df: pd.Series | pd.DatetimeIndex,
rechunk: bool = True,
nan_to_none: bool = True,
) -> Series:
...


def from_pandas(
df: Union["pd.DataFrame", "pd.Series", "pd.DatetimeIndex"],
df: pd.DataFrame | pd.Series | pd.DatetimeIndex,
rechunk: bool = True,
nan_to_none: bool = True,
) -> Union[DataFrame, Series]:
) -> DataFrame | Series:
"""
Construct a Polars DataFrame or Series from a pandas DataFrame or Series.
Expand Down

0 comments on commit 98e321d

Please sign in to comment.