Skip to content

Commit

Permalink
[mypy] Add error codes (#4072)
Browse files Browse the repository at this point in the history
  • Loading branch information
stinodego committed Jul 18, 2022
1 parent 139db59 commit bc1a498
Show file tree
Hide file tree
Showing 29 changed files with 122 additions and 123 deletions.
2 changes: 1 addition & 1 deletion py-polars/polars/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def from_dict(
└─────┴─────┘
"""
return DataFrame._from_dict(data=data, columns=columns) # type: ignore
return DataFrame._from_dict(data=data, columns=columns) # type: ignore[arg-type]


def from_dicts(
Expand Down
14 changes: 7 additions & 7 deletions py-polars/polars/datatypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
except ImportError:
_PYARROW_AVAILABLE = False

from _ctypes import _SimpleCData # type: ignore
from _ctypes import _SimpleCData # type: ignore[import]

try:
from polars.polars import dtype_str_repr
Expand All @@ -27,7 +27,7 @@ class DataType:
Base class for all Polars data types.
"""

def __new__(cls, *args, **kwargs) -> PolarsDataType: # type: ignore
def __new__(cls, *args: Any, **kwargs: Any) -> PolarsDataType: # type: ignore[misc]
# this formulation allows for equivalent use of "pl.Type" and "pl.Type()", while
# still respecting types that take initialisation params (eg: Duration/Datetime)
if args or kwargs:
Expand Down Expand Up @@ -115,7 +115,7 @@ def __init__(self, inner: type[DataType]):
"""
self.inner = py_type_to_dtype(inner)

def __eq__(self, other: type[DataType]) -> bool: # type: ignore
def __eq__(self, other: type[DataType]) -> bool: # type: ignore[override]
# The comparison allows comparing objects to classes
# and specific inner types to none specific.
# if one of the arguments is not specific about its inner type
Expand Down Expand Up @@ -161,7 +161,7 @@ def __init__(self, time_unit: str = "us", time_zone: str | None = None):
self.tu = time_unit
self.tz = time_zone

def __eq__(self, other: type[DataType]) -> bool: # type: ignore
def __eq__(self, other: type[DataType]) -> bool: # type: ignore[override]
# allow comparing object instances to class
if type(other) is type and issubclass(other, Datetime):
return True
Expand All @@ -188,7 +188,7 @@ def __init__(self, time_unit: str = "us"):
"""
self.tu = time_unit

def __eq__(self, other: type[DataType]) -> bool: # type: ignore
def __eq__(self, other: type[DataType]) -> bool: # type: ignore[override]
# allow comparing object instances to class
if type(other) is type and issubclass(other, Duration):
return True
Expand Down Expand Up @@ -228,7 +228,7 @@ def __init__(self, name: str, dtype: type[DataType]):
self.name = name
self.dtype = py_type_to_dtype(dtype)

def __eq__(self, other: Field) -> bool: # type: ignore
def __eq__(self, other: Field) -> bool: # type: ignore[override]
return (self.name == other.name) & (self.dtype == other.dtype)

def __repr__(self) -> str:
Expand All @@ -251,7 +251,7 @@ def __init__(self, fields: Sequence[Field]):
"""
self.fields = fields

def __eq__(self, other: type[DataType]) -> bool: # type: ignore
def __eq__(self, other: type[DataType]) -> bool: # type: ignore[override]
# The comparison allows comparing objects to classes
# and specific inner types to none specific.
# if one of the arguments is not specific about its inner type
Expand Down
2 changes: 1 addition & 1 deletion py-polars/polars/internals/anonymous_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def _scan_ds_impl(
"""
if not _PYARROW_AVAILABLE: # pragma: no cover
raise ImportError("'pyarrow' is required for scanning from pyarrow datasets.")
return pl.from_arrow(ds.to_table(columns=with_columns)) # type: ignore
return pl.from_arrow(ds.to_table(columns=with_columns)) # type: ignore[return-value]


def _scan_ds(ds: pa.dataset.dataset) -> pli.LazyFrame:
Expand Down
2 changes: 1 addition & 1 deletion py-polars/polars/internals/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ def _pandas_series_to_arrow(
"""
dtype = values.dtype
if dtype == "object" and len(values) > 0:
first_non_none = _get_first_non_none(values.values) # type: ignore
first_non_none = _get_first_non_none(values.values) # type: ignore[arg-type]

if isinstance(first_non_none, str):
return pa.array(values, pa.large_utf8(), from_pandas=nan_to_none)
Expand Down
4 changes: 2 additions & 2 deletions py-polars/polars/internals/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -4220,7 +4220,7 @@ def sign(self) -> Expr:
"""
if not _NUMPY_AVAILABLE:
raise ImportError("'numpy' is required for this functionality.")
return np.sign(self) # type: ignore
return np.sign(self) # type: ignore[call-overload]

def sin(self) -> Expr:
"""
Expand Down Expand Up @@ -5173,7 +5173,7 @@ def concat(
if not isinstance(other, list):
other_list = [other]
else:
other_list = copy.copy(other) # type: ignore
other_list = copy.copy(other) # type: ignore[arg-type]

other_list.insert(0, wrap_expr(self._pyexpr))
return pli.concat_list(other_list)
Expand Down
22 changes: 11 additions & 11 deletions py-polars/polars/internals/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def __init__(cls, name: str, bases: tuple, clsdict: dict) -> None:
# LazyFrame subclass by setting `cls._lazyframe_class`. We must therefore
# dynamically create a subclass of LazyFrame with `_dataframe_class` set
# to `cls` in order to preserve types after `.lazy().collect()` roundtrips.
cls._lazyframe_class = type( # type: ignore
cls._lazyframe_class = type( # type: ignore[assignment]
f"Lazy{name}",
(LazyFrame,),
{"_dataframe_class": cls},
Expand Down Expand Up @@ -289,14 +289,14 @@ class DataFrame(metaclass=DataFrameMetaClass):

def __init__(
self,
data: None
| (
data: (
dict[str, Sequence[Any]]
| Sequence[Any]
| np.ndarray
| pa.Table
| pd.DataFrame
| pli.Series
| None
) = None,
columns: ColumnsType | None = None,
orient: Literal["col", "row"] | None = None,
Expand Down Expand Up @@ -1519,10 +1519,10 @@ def to_numpy(self) -> np.ndarray:
else:
return out

def __getstate__(self): # type: ignore
def __getstate__(self) -> list[pli.Series]:
return self.get_columns()

def __setstate__(self, state): # type: ignore
def __setstate__(self, state) -> None: # type: ignore[no-untyped-def]
self._df = DataFrame(state)._df

def __mul__(self: DF, other: DataFrame | pli.Series | int | float | bool) -> DF:
Expand Down Expand Up @@ -1750,7 +1750,7 @@ def __getitem__(

# df[:]
if isinstance(item, slice):
return PolarsSlice(self).apply(item) # type: ignore
return PolarsSlice(self).apply(item) # type: ignore[return-value]

# select rows by numpy mask or index
# df[[1, 2, 3]]
Expand Down Expand Up @@ -1827,7 +1827,7 @@ def __setitem__(
if isinstance(col_selection, str):
s = self.__getitem__(col_selection)
elif isinstance(col_selection, int):
s = self[:, col_selection] # type: ignore
s = self[:, col_selection] # type: ignore[assignment]
else:
raise ValueError(f"column selection not understood: {col_selection}")

Expand Down Expand Up @@ -2890,7 +2890,7 @@ def groupby(
by = [by]
return GroupBy(
self._df,
by, # type: ignore
by, # type: ignore[arg-type]
dataframe_class=self.__class__,
maintain_order=maintain_order,
)
Expand Down Expand Up @@ -4192,7 +4192,7 @@ def clone(self: DF) -> DF:
def __copy__(self: DF) -> DF:
return self.clone()

def __deepcopy__(self: DF, memodict={}) -> DF: # type: ignore
def __deepcopy__(self: DF, memodict: dict = {}) -> DF:
return self.clone()

def get_columns(self) -> list[pli.Series]:
Expand Down Expand Up @@ -4904,7 +4904,7 @@ def select(
"""
return (
self.lazy()
.select(exprs) # type: ignore
.select(exprs) # type: ignore[arg-type]
.collect(no_optimization=True, string_cache=False)
)

Expand Down Expand Up @@ -6165,7 +6165,7 @@ def get_group(self, group_value: Any | tuple[Any]) -> DF:

# should be only one match
try:
groups_idx = groups[mask][0] # type: ignore
groups_idx = groups[mask][0] # type: ignore[index]
except IndexError:
raise ValueError(f"no group: {group_value} found")

Expand Down
2 changes: 1 addition & 1 deletion py-polars/polars/internals/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def concat(
elif isinstance(first, pli.Expr):
out = first
for e in items[1:]:
out = out.append(e) # type: ignore
out = out.append(e) # type: ignore[arg-type]
else:
raise ValueError(f"did not expect type: {type(first)} in 'pl.concat'.")

Expand Down
8 changes: 4 additions & 4 deletions py-polars/polars/internals/lazy_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def _dataframe_class(self) -> type[DF]:
This property is dynamically overwritten when DataFrame is sub-classed. See
`polars.internals.frame.DataFrameMetaClass.__init__` for implementation details.
"""
return pli.DataFrame # type: ignore
return pli.DataFrame # type: ignore[return-value]

@classmethod
def scan_csv(
Expand Down Expand Up @@ -195,7 +195,7 @@ def scan_parquet(
scan = scan.head(n_rows)
if row_count_name is not None:
scan = scan.with_row_count(row_count_name, row_count_offset)
return scan # type: ignore
return scan # type: ignore[return-value]

self = cls.__new__(cls)
self._ldf = PyLazyFrame.new_from_parquet(
Expand Down Expand Up @@ -235,7 +235,7 @@ def scan_ipc(
scan = scan.head(n_rows)
if row_count_name is not None:
scan = scan.with_row_count(row_count_name, row_count_offset)
return scan # type: ignore
return scan # type: ignore[return-value]

self = cls.__new__(cls)
self._ldf = PyLazyFrame.new_from_ipc(
Expand Down Expand Up @@ -809,7 +809,7 @@ def clone(self: LDF) -> LDF:
def __copy__(self: LDF) -> LDF:
return self.clone()

def __deepcopy__(self: LDF, memodict={}) -> LDF: # type: ignore
def __deepcopy__(self: LDF, memodict: dict = {}) -> LDF:
return self.clone()

def filter(self: LDF, predicate: pli.Expr | str) -> LDF:
Expand Down
6 changes: 3 additions & 3 deletions py-polars/polars/internals/lazy_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def col(
"""
if isinstance(name, pli.Series):
name = name.to_list() # type: ignore
name = name.to_list() # type: ignore[assignment]

# note: we need the typing.cast call here twice to make mypy happy under Python 3.7
# On Python 3.10, it is not needed. We use cast as it works across versions, ignoring
Expand Down Expand Up @@ -685,7 +685,7 @@ def lit(
# numpy literals like np.float32(0)
# have an item
if hasattr(value, "item"):
value = value.item() # type: ignore
value = value.item() # type: ignore[union-attr]
return pli.wrap_expr(pylit(value))


Expand Down Expand Up @@ -1697,7 +1697,7 @@ def repeat(
if name is None:
name = ""
dtype = py_type_to_dtype(type(value))
s = pli.Series._repeat(name, value, n, dtype) # type: ignore
s = pli.Series._repeat(name, value, n, dtype) # type: ignore[arg-type]
return s
else:
if isinstance(n, int):
Expand Down
8 changes: 4 additions & 4 deletions py-polars/polars/internals/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -2286,7 +2286,7 @@ def to_numpy(
kwargs will be sent to pyarrow.Array.to_numpy
"""

def convert_to_date(arr): # type: ignore
def convert_to_date(arr): # type: ignore[no-untyped-def]
if self.dtype == Date:
tp = "datetime64[D]"
elif self.dtype == Duration:
Expand Down Expand Up @@ -2591,7 +2591,7 @@ def sign(self) -> Series:
"""
if not _NUMPY_AVAILABLE:
raise ImportError("'numpy' is required for this functionality.")
return np.sign(self) # type: ignore
return np.sign(self) # type: ignore[return-value]

def sin(self) -> Series:
"""
Expand Down Expand Up @@ -5423,13 +5423,13 @@ def min(self) -> date | datetime | timedelta:
Return minimum as python DateTime
"""
# we can ignore types because we are certain we get a logical type
return wrap_s(self._s).min() # type: ignore
return wrap_s(self._s).min() # type: ignore[return-value]

def max(self) -> date | datetime | timedelta:
"""
Return maximum as python DateTime
"""
return wrap_s(self._s).max() # type: ignore
return wrap_s(self._s).max() # type: ignore[return-value]

def median(self) -> date | datetime | timedelta:
"""
Expand Down
2 changes: 1 addition & 1 deletion py-polars/polars/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -1056,7 +1056,7 @@ def read_excel(
"""

try:
import xlsx2csv # type: ignore
import xlsx2csv # type: ignore[import]
except ImportError:
raise ImportError(
"xlsx2csv is not installed. Please run `pip install xlsx2csv`."
Expand Down
4 changes: 2 additions & 2 deletions py-polars/polars/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,8 @@ def assert_frame_equal(
# this does not assume a particular order
for c in left.columns:
_assert_series_inner(
left[c], # type: ignore
right[c], # type: ignore
left[c], # type: ignore[arg-type, index]
right[c], # type: ignore[arg-type, index]
check_dtype,
check_exact,
nans_compare_equal,
Expand Down
4 changes: 2 additions & 2 deletions py-polars/polars/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,13 @@ def handle_projection_columns(
projection: list[int] | None = None
if columns:
if is_int_sequence(columns):
projection = columns # type: ignore
projection = columns # type: ignore[assignment]
columns = None
elif not is_str_sequence(columns):
raise ValueError(
"columns arg should contain a list of all integers or all strings values."
)
return projection, columns # type: ignore
return projection, columns # type: ignore[return-value]


def _to_python_time(value: int) -> time:
Expand Down
3 changes: 1 addition & 2 deletions py-polars/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ warn_redundant_casts = true
enable_error_code = [
"redundant-expr",
"truthy-bool",
# TODO: Uncomment error below and fix mypy errors
# "ignore-without-code",
"ignore-without-code",
]

[[tool.mypy.overrides]]
Expand Down
4 changes: 2 additions & 2 deletions py-polars/tests/io/test_avro.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def compressions() -> list[str]:
def test_from_to_buffer(example_df: pl.DataFrame, compressions: list[str]) -> None:
for compression in compressions:
buf = io.BytesIO()
example_df.write_avro(buf, compression=compression) # type: ignore
example_df.write_avro(buf, compression=compression) # type: ignore[arg-type]
buf.seek(0)
read_df = pl.read_avro(buf)
assert example_df.frame_equal(read_df)
Expand All @@ -33,7 +33,7 @@ def test_from_to_file(
f = os.path.join(io_test_dir, "small.avro")

for compression in compressions:
example_df.write_avro(f, compression=compression) # type: ignore
example_df.write_avro(f, compression=compression) # type: ignore[arg-type]
df_read = pl.read_avro(str(f))
assert example_df.frame_equal(df_read)

Expand Down

0 comments on commit bc1a498

Please sign in to comment.