Skip to content

Commit

Permalink
chore(python): Enable new error message lint to improve stack trace d…
Browse files Browse the repository at this point in the history
…isplay (pola-rs#13596)
  • Loading branch information
stinodego authored Jan 10, 2024
1 parent 505ec71 commit 28a58cf
Show file tree
Hide file tree
Showing 59 changed files with 693 additions and 626 deletions.
9 changes: 6 additions & 3 deletions py-polars/polars/_cpu_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ class CPUID_struct(ctypes.Structure):
class CPUID:
def __init__(self) -> None:
if _POLARS_ARCH != "x86-64":
raise SystemError("CPUID is only available for x86")
msg = "CPUID is only available for x86"
raise SystemError(msg)

if _IS_WINDOWS:
if _IS_64BIT:
Expand Down Expand Up @@ -156,7 +157,8 @@ def __init__(self) -> None:
None, size, _MEM_COMMIT | _MEM_RESERVE, _PAGE_EXECUTE_READWRITE
)
if not self.addr:
raise MemoryError("could not allocate memory for CPUID check")
msg = "could not allocate memory for CPUID check"
raise MemoryError(msg)
ctypes.memmove(self.addr, code, size)
else:
import mmap # Only import if necessary.
Expand Down Expand Up @@ -225,7 +227,8 @@ def check_cpu_flags() -> None:
missing_features = []
for f in expected_cpu_flags:
if f not in supported_cpu_flags:
raise RuntimeError(f'unknown feature flag "{f}"')
msg = f'unknown feature flag "{f}"'
raise RuntimeError(msg)

if not supported_cpu_flags[f]:
missing_features.append(f)
Expand Down
3 changes: 2 additions & 1 deletion py-polars/polars/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ def _create_namespace(

def namespace(ns_class: type[NS]) -> type[NS]:
if name in _reserved_namespaces:
raise AttributeError(f"cannot override reserved namespace {name!r}")
msg = f"cannot override reserved namespace {name!r}"
raise AttributeError(msg)
elif hasattr(cls, name):
warn(
f"Overriding existing custom namespace {name!r} (on {cls.__name__!r})",
Expand Down
40 changes: 20 additions & 20 deletions py-polars/polars/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@ def __init__(self, *, restore_defaults: bool = False, **options: Any) -> None:
if not hasattr(self, opt) and not opt.startswith("set_"):
opt = f"set_{opt}"
if not hasattr(self, opt):
raise AttributeError(f"`Config` has no option {opt!r}")
msg = f"`Config` has no option {opt!r}"
raise AttributeError(msg)
getattr(self, opt)(value)

def __enter__(self) -> Config:
Expand Down Expand Up @@ -193,9 +194,8 @@ def load(cls, cfg: str) -> type[Config]:
try:
options = json.loads(cfg)
except json.JSONDecodeError as err:
raise ValueError(
"invalid Config string (did you mean to use `load_from_file`?)"
) from err
msg = "invalid Config string (did you mean to use `load_from_file`?)"
raise ValueError(msg) from err

os.environ.update(options.get("environment", {}))
for cfg_methodname, value in options.get("direct", {}).items():
Expand All @@ -221,9 +221,8 @@ def load_from_file(cls, file: Path | str) -> type[Config]:
try:
options = Path(normalize_filepath(file)).read_text()
except OSError as err:
raise ValueError(
f"invalid Config file (did you mean to use `load`?)\n{err}"
) from err
msg = f"invalid Config file (did you mean to use `load`?)\n{err}"
raise ValueError(msg) from err

return cls.load(options)

Expand Down Expand Up @@ -456,9 +455,8 @@ def set_decimal_separator(cls, separator: str | None = None) -> type[Config]:
└───────────────┘
"""
if isinstance(separator, str) and len(separator) != 1:
raise ValueError(
f"`separator` must be a single character; found {separator!r}"
)
msg = f"`separator` must be a single character; found {separator!r}"
raise ValueError(msg)
plr.set_decimal_separator(sep=separator)
return cls

Expand Down Expand Up @@ -526,9 +524,8 @@ def set_thousands_separator(
plr.set_thousands_separator(sep=",")
else:
if isinstance(separator, str) and len(separator) > 1:
raise ValueError(
f"`separator` must be a single character; found {separator!r}"
)
msg = f"`separator` must be a single character; found {separator!r}"
raise ValueError(msg)
plr.set_thousands_separator(sep=separator or None)
return cls

Expand Down Expand Up @@ -689,7 +686,8 @@ def set_fmt_str_lengths(cls, n: int | None) -> type[Config]:
os.environ.pop("POLARS_FMT_STR_LEN", None)
else:
if n <= 0:
raise ValueError("number of characters must be > 0")
msg = "number of characters must be > 0"
raise ValueError(msg)

os.environ["POLARS_FMT_STR_LEN"] = str(n)
return cls
Expand Down Expand Up @@ -763,7 +761,8 @@ def set_streaming_chunk_size(cls, size: int | None) -> type[Config]:
os.environ.pop("POLARS_STREAMING_CHUNK_SIZE", None)
else:
if size < 1:
raise ValueError("number of rows per chunk must be >= 1")
msg = "number of rows per chunk must be >= 1"
raise ValueError(msg)

os.environ["POLARS_STREAMING_CHUNK_SIZE"] = str(size)
return cls
Expand Down Expand Up @@ -807,7 +806,8 @@ def set_tbl_cell_alignment(
if format is None:
os.environ.pop("POLARS_FMT_TABLE_CELL_ALIGNMENT", None)
elif format not in {"LEFT", "CENTER", "RIGHT"}:
raise ValueError(f"invalid alignment: {format!r}")
msg = f"invalid alignment: {format!r}"
raise ValueError(msg)
else:
os.environ["POLARS_FMT_TABLE_CELL_ALIGNMENT"] = format
return cls
Expand Down Expand Up @@ -856,7 +856,8 @@ def set_tbl_cell_numeric_alignment(
if format is None:
os.environ.pop("POLARS_FMT_TABLE_CELL_NUMERIC_ALIGNMENT", None)
elif format not in {"LEFT", "CENTER", "RIGHT"}:
raise ValueError(f"invalid alignment: {format!r}")
msg = f"invalid alignment: {format!r}"
raise ValueError(msg)
else:
os.environ["POLARS_FMT_TABLE_CELL_NUMERIC_ALIGNMENT"] = format
return cls
Expand Down Expand Up @@ -1024,9 +1025,8 @@ def set_tbl_formatting(
else:
valid_format_names = get_args(TableFormatNames)
if format not in valid_format_names:
raise ValueError(
f"invalid table format name: {format!r}\nExpected one of: {', '.join(valid_format_names)}"
)
msg = f"invalid table format name: {format!r}\nExpected one of: {', '.join(valid_format_names)}"
raise ValueError(msg)
os.environ["POLARS_FMT_TABLE_FORMATTING"] = format

if rounded_corners is None:
Expand Down
19 changes: 10 additions & 9 deletions py-polars/polars/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,8 @@ def from_dicts(
└─────┴─────┴──────┴──────┘
"""
if not data and not (schema or schema_overrides):
raise NoDataError("no data, cannot infer schema")
msg = "no data, cannot infer schema"
raise NoDataError(msg)

return pl.DataFrame(
data,
Expand Down Expand Up @@ -294,9 +295,10 @@ def _from_dataframe_repr(m: re.Match[str]) -> DataFrame:
data.extend((pl.Series(empty_data, dtype=String)) for _ in range(n_extend_cols))
for dtype in set(schema.values()):
if dtype in (List, Struct, Object):
raise NotImplementedError(
msg = (
f"`from_repr` does not support data type {dtype.base_type().__name__!r}"
)
raise NotImplementedError(msg)

# construct DataFrame from string series and cast from repr to native dtype
df = pl.DataFrame(data=data, orient="col", schema=list(schema))
Expand Down Expand Up @@ -441,7 +443,8 @@ def from_repr(tbl: str) -> DataFrame | Series:
if m is not None:
return _from_series_repr(m)

raise ValueError("input string does not contain DataFrame or Series")
msg = "input string does not contain DataFrame or Series"
raise ValueError(msg)


def from_numpy(
Expand Down Expand Up @@ -617,9 +620,8 @@ def from_arrow(
schema_overrides=schema_overrides,
)

raise TypeError(
f"expected PyArrow Table, Array, or one or more RecordBatches; got {type(data).__name__!r}"
)
msg = f"expected PyArrow Table, Array, or one or more RecordBatches; got {type(data).__name__!r}"
raise TypeError(msg)


@overload
Expand Down Expand Up @@ -721,9 +723,8 @@ def from_pandas(
include_index=include_index,
)
else:
raise TypeError(
f"expected pandas DataFrame or Series, got {type(data).__name__!r}"
)
msg = f"expected pandas DataFrame or Series, got {type(data).__name__!r}"
raise TypeError(msg)


def from_dataframe(df: SupportsInterchange, *, allow_copy: bool = True) -> DataFrame:
Expand Down
Loading

0 comments on commit 28a58cf

Please sign in to comment.