Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace black, flake8 and isort with ruff #95

Merged
merged 7 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 7 additions & 12 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,14 @@ repos:
hooks:
- id: check-merge-conflict
- id: debug-statements
- repo: https://github.com/PyCQA/isort
rev: "5.12.0"
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.6.8
hooks:
- id: isort
additional_dependencies: [toml]
- repo: https://github.com/psf/black
rev: "23.1.0"
hooks:
- id: black
# - repo: https://github.com/PyCQA/flake8
# rev: 6.0.0
# hooks:
# - id: flake8
- id: ruff
types_or: [python]
args: [--fix]
- id: ruff-format
types_or: [python]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: "v0.991"
hooks:
Expand Down
5 changes: 2 additions & 3 deletions csvy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""
Python reader/writer for CSV files with YAML header information.
"""
"""Python reader/writer for CSV files with YAML header information."""

__version__ = "0.2.2"
from .readers import ( # noqa: F401
read_header,
Expand Down
38 changes: 20 additions & 18 deletions csvy/readers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""A collection of functions for parsing CSVY files."""

import logging
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
from typing import Any

import yaml

Expand Down Expand Up @@ -45,8 +47,8 @@ def get_comment(line: str, marker: str = "---") -> str:


def read_header(
filename: Union[Path, str], marker: str = "---", **kwargs: Any
) -> Tuple[Dict[str, Any], int, str]:
filename: Path | str, marker: str = "---", **kwargs: Any
) -> tuple[dict[str, Any], int, str]:
"""Read the yaml-formatted header from a file.

Args:
Expand Down Expand Up @@ -80,8 +82,8 @@ def read_header(


def read_metadata(
filename: Union[Path, str], marker: str = "---", **kwargs: Any
) -> Dict[str, Any]:
filename: Path | str, marker: str = "---", **kwargs: Any
) -> dict[str, Any]:
"""Read the yaml-formatted metadata from a file.

Args:
Expand All @@ -96,11 +98,11 @@ def read_metadata(


def read_to_array(
filename: Union[Path, str],
filename: Path | str,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In theory, this syntax is not valid for Python 3.9. See https://www.slingacademy.com/article/union-type-in-python-the-complete-guide/#:~:text=Introduced%20in%20Python%203.10%20as%20part%20of%20PEP

I think this might be running the ruff pre-commit with the wrong python version. Could you add a default python version in the pre-commit-congig.yml file? See https://pre-commit.com/#top_level-default_language_version

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So in readers.py you've got from __future__ import annotations, so the | operator should be valid. Not sure why it's not complaining in writers.py though!

That said, when I run ruff check --target-version py39 it doesn't complain - weird!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I forgot about the __futures__ stuff. Yeah, with that all of that should work. But I agree it should fail if not imported.

marker: str = "---",
csv_options: Optional[Dict[str, Any]] = None,
yaml_options: Optional[Dict[str, Any]] = None,
) -> Tuple[NDArray, Dict[str, Any]]:
csv_options: dict[str, Any] | None = None,
yaml_options: dict[str, Any] | None = None,
) -> tuple[NDArray, dict[str, Any]]:
"""Reads a CSVY file into dict with the header and array with the data.

Args:
Expand Down Expand Up @@ -131,11 +133,11 @@ def read_to_array(


def read_to_dataframe(
filename: Union[Path, str],
filename: Path | str,
marker: str = "---",
csv_options: Optional[Dict[str, Any]] = None,
yaml_options: Optional[Dict[str, Any]] = None,
) -> Tuple[DataFrame, Dict[str, Any]]:
csv_options: dict[str, Any] | None = None,
yaml_options: dict[str, Any] | None = None,
) -> tuple[DataFrame, dict[str, Any]]:
"""Reads a CSVY file into dict with the header and a DataFrame with the data.

Possible 'skiprows' and 'comment' argument provided in the 'csv_options' dictionary
Expand Down Expand Up @@ -169,11 +171,11 @@ def read_to_dataframe(


def read_to_list(
filename: Union[Path, str],
filename: Path | str,
marker: str = "---",
csv_options: Optional[Dict[str, Any]] = None,
yaml_options: Optional[Dict[str, Any]] = None,
) -> Tuple[List[List], Dict[str, Any]]:
csv_options: dict[str, Any] | None = None,
yaml_options: dict[str, Any] | None = None,
) -> tuple[list[list], dict[str, Any]]:
"""Reads a CSVY file into a list with the header and a nested list with the data.

Args:
Expand All @@ -196,7 +198,7 @@ def read_to_list(
options = csv_options.copy() if csv_options is not None else {}

data = []
with open(filename, "r", newline="") as csvfile:
with open(filename, newline="") as csvfile:
csvreader = csv.reader(csvfile, **options)

for _ in range(nlines):
Expand Down
49 changes: 30 additions & 19 deletions csvy/writers.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,40 @@
"""A collection of functions for writing CSVY files."""

from __future__ import annotations

import csv
import logging
from collections.abc import Callable, Iterable
from io import TextIOBase
from pathlib import Path
from typing import Any, Callable, Dict, Iterable, List, Optional, Union
from typing import Any

import yaml

KNOWN_WRITERS: List[Callable[[Union[Path, str], Any, str], bool]] = []
KNOWN_WRITERS: list[Callable[[Path | str, Any, str], bool]] = []


def register_writer(fun: Callable[[Path | str, Any, str], bool]) -> Callable:
"""Register a file writer.

Args:
fun (Callable): The writer function.

def register_writer(fun: Callable[[Union[Path, str], Any, str], bool]) -> Callable:
Returns:
Callable: the writer function.
"""
if fun not in KNOWN_WRITERS:
KNOWN_WRITERS.append(fun)
return fun


def write(
filename: Union[Path, str],
filename: Path | str,
data: Any,
header: Dict[str, Any],
header: dict[str, Any],
comment: str = "",
csv_options: Optional[Dict[str, Any]] = None,
yaml_options: Optional[Dict[str, Any]] = None,
csv_options: dict[str, Any] | None = None,
yaml_options: dict[str, Any] | None = None,
) -> None:
"""Writes the data and header in a CSV file, formating the header as yaml.

Expand Down Expand Up @@ -54,11 +65,11 @@ class Writer:

def __init__(
self,
filename: Union[Path, str],
header: Dict[str, Any],
filename: Path | str,
header: dict[str, Any],
comment: str = "",
csv_options: Optional[Dict[str, Any]] = None,
yaml_options: Optional[Dict[str, Any]] = None,
csv_options: dict[str, Any] | None = None,
yaml_options: dict[str, Any] | None = None,
line_buffering: bool = False,
) -> None:
"""Create a new Writer.
Expand All @@ -72,7 +83,6 @@ def __init__(
writing the header.
line_buffering: Line buffering instead of chunk buffering (default False).
"""

if not csv_options:
csv_options = {}
if not yaml_options:
Expand All @@ -88,9 +98,11 @@ def __init__(
self._writer = csv.writer(self._file, **csv_options)

def __enter__(self) -> Writer:
"""Enter the context manager."""
return self

def __exit__(self, *_: Any) -> None:
"""Exit the context manager."""
self._file.close()

def close(self) -> None:
Expand All @@ -107,8 +119,8 @@ def writerows(self, rows: Iterable[Iterable[Any]]) -> None:


def write_header(
file: Union[Path, str, TextIOBase],
header: Dict[str, Any],
file: Path | str | TextIOBase,
header: dict[str, Any],
comment: str = "",
**kwargs: Any,
) -> None:
Expand Down Expand Up @@ -137,7 +149,7 @@ def write_header(


def write_data(
filename: Union[Path, str], data: Any, comment: str = "", **kwargs: Any
filename: Path | str, data: Any, comment: str = "", **kwargs: Any
) -> None:
"""Writes the tabular data to the chosen file, adding it after the header.

Expand All @@ -160,7 +172,7 @@ def write_data(

@register_writer
def write_numpy(
filename: Union[Path, str], data: Any, comment: str = "", **kwargs: Any
filename: Path | str, data: Any, comment: str = "", **kwargs: Any
) -> bool:
"""Writes the numpy array to the chosen file, adding it after the header.

Expand Down Expand Up @@ -193,7 +205,7 @@ def write_numpy(

@register_writer
def write_pandas(
filename: Union[Path, str], data: Any, comment: str = "", **kwargs: Any
filename: Path | str, data: Any, comment: str = "", **kwargs: Any
) -> bool:
"""Writes the pandas dataframe to the chosen file, adding it after the header.

Expand Down Expand Up @@ -224,7 +236,7 @@ def write_pandas(


def write_csv(
filename: Union[Path, str], data: Any, comment: str = "", **kwargs: Any
filename: Path | str, data: Any, comment: str = "", **kwargs: Any
) -> bool:
"""Writes the tabular to the chosen file, adding it after the header.

Expand All @@ -239,7 +251,6 @@ def write_csv(
Returns:
True if the writer worked, False otherwise.
"""

with open(filename, "a", newline="") as f:
writer = csv.writer(f, **kwargs)
for row in data:
Expand Down
Loading
Loading