Skip to content

Commit

Permalink
Fix ruff formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
trossi committed Oct 28, 2024
1 parent 25a14af commit 7984089
Show file tree
Hide file tree
Showing 9 changed files with 72 additions and 61 deletions.
1 change: 1 addition & 0 deletions rdata/_write.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Functions to perform conversion and unparsing in one step."""

from __future__ import annotations

from typing import TYPE_CHECKING
Expand Down
1 change: 1 addition & 0 deletions rdata/conversion/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Utilities for converting R objects to Python ones."""

from ._conversion import (
DEFAULT_CLASS_MAP as DEFAULT_CLASS_MAP,
Converter as Converter,
Expand Down
67 changes: 35 additions & 32 deletions rdata/conversion/to_r.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@

class Converter(Protocol):
"""Protocol for class converting Python objects to R objects."""

format_version: int

def convert_to_r_sym(self, name: str) -> RObject:
Expand Down Expand Up @@ -122,10 +123,7 @@ def dataframe_constructor(
index = data.index
if isinstance(index, pd.RangeIndex):
assert isinstance(index.start, int)
if (index.start == 1
and index.stop == data.shape[0] + 1
and index.step == 1
):
if index.start == 1 and index.stop == data.shape[0] + 1 and index.step == 1:
row_names = np.ma.array(
data=[R_INT_NA, -data.shape[0]],
mask=[True, False],
Expand All @@ -134,8 +132,7 @@ def dataframe_constructor(
else:
row_names = index
elif isinstance(index, pd.Index):
if (index.dtype == "object"
or np.issubdtype(str(index.dtype), np.integer)):
if index.dtype == "object" or np.issubdtype(str(index.dtype), np.integer):
row_names = index.to_numpy()
else:
msg = f"pd.DataFrame pd.Index {index.dtype} not implemented"
Expand Down Expand Up @@ -296,10 +293,11 @@ def build_r_object(
"""
assert r_type is not None
reference_id, referenced_object = reference
assert ((reference_id == 0)
== (referenced_object is None)
== (r_type != RObjectType.REF)
)
assert (
(reference_id == 0)
== (referenced_object is None)
== (r_type != RObjectType.REF)
)
return RObject(
RObjectInfo(
r_type,
Expand All @@ -308,12 +306,12 @@ def build_r_object(
tag=tag is not None,
gp=gp,
reference=reference_id,
),
value,
attributes,
tag,
referenced_object,
)
),
value,
attributes,
tag,
referenced_object,
)


def build_r_list(
Expand Down Expand Up @@ -393,7 +391,10 @@ class ConverterFromPythonToR:
r_version_serialized: R version written as the creator of the object.
constructor_dict: Dictionary mapping Python types to R classes.
"""
def __init__(self, *,

def __init__(
self,
*,
encoding: Encoding = "utf-8",
format_version: int = DEFAULT_FORMAT_VERSION,
r_version_serialized: int = DEFAULT_R_VERSION_SERIALIZED,
Expand All @@ -412,11 +413,12 @@ def __init__(self, *,
self.format_version = format_version
self.r_version_serialized = r_version_serialized
self.constructor_dict = constructor_dict
self._references: dict[str | None, tuple[int, RObject | None]] \
= {None: (0, None)}
self._references: dict[str | None, tuple[int, RObject | None]] = {
None: (0, None),
}


def convert_to_r_data(self,
def convert_to_r_data(
self,
data: Any, # noqa: ANN401
*,
file_type: FileType = "rds",
Expand Down Expand Up @@ -451,14 +453,16 @@ def convert_to_r_data(self,
R_MINIMUM_VERSIONS[self.format_version],
)

extra = (RExtraInfo(self.encoding.upper())
if versions.format >= R_MINIMUM_VERSION_WITH_ENCODING
else RExtraInfo(None))
extra = (
RExtraInfo(self.encoding.upper())
if versions.format >= R_MINIMUM_VERSION_WITH_ENCODING
else RExtraInfo(None)
)

return RData(versions, extra, r_object)


def convert_to_r_attributes(self,
def convert_to_r_attributes(
self,
data: dict[str, Any],
) -> RObject:
"""
Expand All @@ -479,8 +483,8 @@ def convert_to_r_attributes(self,

return build_r_list(converted)


def convert_to_r_sym(self,
def convert_to_r_sym(
self,
name: str,
) -> RObject:
"""
Expand All @@ -507,8 +511,8 @@ def convert_to_r_sym(self,
self._references[name] = (len(self._references), r_object)
return r_object


def convert_to_r_object(self, # noqa: C901, PLR0912, PLR0915
def convert_to_r_object( # noqa: C901, PLR0912, PLR0915
self,
data: Any, # noqa: ANN401
) -> RObject:
"""
Expand Down Expand Up @@ -583,8 +587,7 @@ def convert_to_r_object(self, # noqa: C901, PLR0912, PLR0915
elif data.dtype.kind in ["U"]:
assert data.ndim == 1
r_type = RObjectType.STR
r_value = [build_r_char(el, encoding=self.encoding)
for el in data]
r_value = [build_r_char(el, encoding=self.encoding) for el in data]

else:
r_type = {
Expand Down
7 changes: 3 additions & 4 deletions rdata/parser/_ascii.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,10 @@ def _readline(self) -> str:
return self.file.readline()[:-1]

def _parse_array_values(
self,
dtype: npt.DTypeLike,
length: int,
self,
dtype: npt.DTypeLike,
length: int,
) -> npt.NDArray[Any]:

array = np.empty(length, dtype=dtype)
value: int | float | complex

Expand Down
6 changes: 3 additions & 3 deletions rdata/parser/_xdr.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ def __init__(
self.file = io.BytesIO(data)

def _parse_array_values(
self,
dtype: npt.DTypeLike,
length: int,
self,
dtype: npt.DTypeLike,
length: int,
) -> npt.NDArray[Any]:
dtype = np.dtype(dtype)
buffer = self.file.read(length * dtype.itemsize)
Expand Down
40 changes: 22 additions & 18 deletions rdata/unparser/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@


def unparse_file(
path: os.PathLike[Any] | str,
r_data: RData,
*,
file_format: FileFormat = "xdr",
file_type: FileType = "rds",
compression: Compression = "gzip",
path: os.PathLike[Any] | str,
r_data: RData,
*,
file_format: FileFormat = "xdr",
file_type: FileType = "rds",
compression: Compression = "gzip",
) -> None:
"""
Unparse RData object to a file.
Expand Down Expand Up @@ -59,11 +59,11 @@ def unparse_file(


def unparse_fileobj(
fileobj: IO[Any],
r_data: RData,
*,
file_format: FileFormat = "xdr",
file_type: FileType = "rds",
fileobj: IO[Any],
r_data: RData,
*,
file_format: FileFormat = "xdr",
file_type: FileType = "rds",
) -> None:
"""
Unparse RData object to a file object.
Expand All @@ -78,9 +78,11 @@ def unparse_fileobj(

if file_format == "ascii":
from ._ascii import UnparserASCII as Unparser

rda_magic = "RDA"
elif file_format == "xdr":
from ._xdr import UnparserXDR as Unparser

rda_magic = "RDX"
else:
msg = f"Unknown file format: {file_format}"
Expand All @@ -89,9 +91,11 @@ def unparse_fileobj(
# Check that RData object for rda file is of correct kind
if file_type == "rda":
r_object = r_data.object
if not (r_object.info.type is RObjectType.LIST
and r_object.tag is not None
and r_object.tag.info.type is RObjectType.SYM):
if not (
r_object.info.type is RObjectType.LIST
and r_object.tag is not None
and r_object.tag.info.type is RObjectType.SYM
):
msg = "r_data object must be dictionary-like for rda file"
raise ValueError(msg)

Expand All @@ -104,10 +108,10 @@ def unparse_fileobj(


def unparse_data(
r_data: RData,
*,
file_format: FileFormat = "xdr",
file_type: FileType = "rds",
r_data: RData,
*,
file_format: FileFormat = "xdr",
file_type: FileType = "rds",
) -> bytes:
"""
Unparse RData object to a bytestring.
Expand Down
5 changes: 3 additions & 2 deletions rdata/unparser/_ascii.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def escape(b: bytes) -> str:
byte_to_str[byte] = escape(bytes([byte]))

# Update mapping for special characters
byte_to_str[b'"'[0]] = r'\"'
byte_to_str[b'"'[0]] = r"\""
byte_to_str[b"'"[0]] = r"\'"
byte_to_str[b"?"[0]] = r"\?"
byte_to_str[b" "[0]] = r"\040"
Expand Down Expand Up @@ -68,7 +68,8 @@ def unparse_magic(self) -> None:
"""Unparse magic bits."""
self._add_line("A")

def _unparse_array_values_raw(self,
def _unparse_array_values_raw(
self,
array: npt.NDArray[np.int32 | np.float64 | np.complex128],
) -> None:
# Convert complex to pairs of floats
Expand Down
3 changes: 2 additions & 1 deletion rdata/unparser/_unparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,8 @@ def _unparse_array_values(self, array: npt.NDArray[Any]) -> None:
self._unparse_array_values_raw(array)

@abc.abstractmethod
def _unparse_array_values_raw(self,
def _unparse_array_values_raw(
self,
array: npt.NDArray[np.int32 | np.float64 | np.complex128],
) -> None:
"""Unparse the values of an array as such."""
Expand Down
3 changes: 2 additions & 1 deletion rdata/unparser/_xdr.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ def unparse_magic(self) -> None:
"""Unparse magic bits."""
self.file.write(b"X\n")

def _unparse_array_values_raw(self,
def _unparse_array_values_raw(
self,
array: npt.NDArray[np.int32 | np.float64 | np.complex128],
) -> None:
# Convert to big endian if needed
Expand Down

0 comments on commit 7984089

Please sign in to comment.