Skip to content

Commit

Permalink
Fix some style things.
Browse files Browse the repository at this point in the history
  • Loading branch information
vnmabus committed Oct 31, 2023
1 parent 247ee37 commit 761a6a8
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 47 deletions.
44 changes: 24 additions & 20 deletions rdata/conversion/_conversion.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
Any,
Callable,
ChainMap,
List,
Final,
Mapping,
MutableMapping,
NamedTuple,
Expand All @@ -33,14 +33,14 @@
class RLanguage(NamedTuple):
"""R language construct."""

elements: List[Any]
elements: list[Any]
attributes: Mapping[str, Any]


class RExpression(NamedTuple):
"""R expression."""

elements: List[RLanguage]
elements: list[RLanguage]


@dataclass
Expand Down Expand Up @@ -96,7 +96,7 @@ def __init__(
def convert_list(
r_list: parser.RObject,
conversion_function: ConversionFunction,
) -> Union[StrMap, List[Any]]:
) -> StrMap | list[Any]:
"""
Expand a tagged R pairlist to a Python dictionary.
Expand Down Expand Up @@ -206,8 +206,8 @@ def convert_attrs(
def convert_vector(
r_vec: parser.RObject,
conversion_function: ConversionFunction,
attrs: Optional[StrMap] = None,
) -> Union[List[Any], StrMap]:
attrs: StrMap | None = None,
) -> list[Any] | StrMap:
"""
Convert a R vector to a Python list or dictionary.
Expand Down Expand Up @@ -243,7 +243,7 @@ def convert_vector(
}:
raise TypeError("Must receive a VEC or EXPR object")

value: Union[List[Any], StrMap] = [
value: list[Any] | StrMap = [
conversion_function(o) for o in r_vec.value
]

Expand All @@ -268,9 +268,9 @@ def safe_decode(byte_str: bytes, encoding: str) -> Union[str, bytes]:

def convert_char(
r_char: parser.RObject,
default_encoding: Optional[str] = None,
default_encoding: str | None = None,
force_default_encoding: bool = False,
) -> Union[str, bytes, None]:
) -> str | bytes | None:
"""
Decode a R character array to a Python string or bytes.
Expand Down Expand Up @@ -331,7 +331,7 @@ def convert_char(
def convert_symbol(
r_symbol: parser.RObject,
conversion_function: ConversionFunction,
) -> Union[str, bytes]:
) -> str | bytes:
"""
Decode a R symbol to a Python string or bytes.
Expand Down Expand Up @@ -364,8 +364,8 @@ def convert_symbol(
def convert_array(
r_array: RObject,
conversion_function: ConversionFunction,
attrs: Optional[StrMap] = None,
) -> Union[np.ndarray, xarray.DataArray]:
attrs: StrMap | None = None,
) -> np.ndarray | xarray.DataArray:
"""
Convert a R array to a Numpy ndarray or a Xarray DataArray.
Expand Down Expand Up @@ -573,7 +573,7 @@ def srcfilecopy_constructor(
Constructor,
]

default_class_map_dict: Mapping[Union[str, bytes], Constructor] = {
default_class_map_dict: Final[Mapping[Union[str, bytes], Constructor]] = {
"data.frame": dataframe_constructor,
"factor": factor_constructor,
"ordered": ordered_constructor,
Expand All @@ -583,7 +583,7 @@ def srcfilecopy_constructor(
"srcfilecopy": srcfilecopy_constructor,
}

DEFAULT_CLASS_MAP = MappingProxyType(default_class_map_dict)
DEFAULT_CLASS_MAP: Final = MappingProxyType(default_class_map_dict)
"""
Default mapping of constructor functions.
Expand All @@ -604,7 +604,7 @@ class Converter(abc.ABC):
"""Interface of a class converting R objects in Python objects."""

@abc.abstractmethod
def convert(self, data: Union[parser.RData, parser.RObject]) -> Any:
def convert(self, data: parser.RData | parser.RObject) -> Any:
"""Convert a R object to a Python one."""
pass

Expand Down Expand Up @@ -638,7 +638,7 @@ def constructor(obj, attrs):
def __init__(
self,
constructor_dict: ConstructorDict = DEFAULT_CLASS_MAP,
default_encoding: Optional[str] = None,
default_encoding: str | None = None,
force_default_encoding: bool = False,
global_environment: MutableMapping[str | bytes, Any] | None = None,
) -> None:
Expand All @@ -660,12 +660,12 @@ def _reset(self) -> None:

def convert( # noqa: D102
self,
data: Union[parser.RData, parser.RObject],
data: parser.RData | parser.RObject,
) -> Any:
self._reset()
return self._convert_next(data)

def _convert_next(self, data: Union[parser.RData, parser.RObject]) -> Any:
def _convert_next(self, data: parser.RData | parser.RObject) -> Any:
"""Convert a R object to a Python one."""
obj: RObject
if isinstance(data, parser.RData):
Expand Down Expand Up @@ -696,6 +696,7 @@ def _convert_next(self, data: Union[parser.RData, parser.RObject]) -> Any:

elif obj.info.type == parser.RObjectType.CLO:
assert obj.tag is not None
assert obj.attributes is not None
environment = self._convert_next(obj.tag)
formals = self._convert_next(obj.value[0])
body = self._convert_next(obj.value[1])
Expand Down Expand Up @@ -725,7 +726,10 @@ def _convert_next(self, data: Union[parser.RData, parser.RObject]) -> Any:

value = RLanguage(rlanguage_list, attributes)

elif obj.info.type in {parser.RObjectType.SPECIAL, parser.RObjectType.BUILTIN}:
elif obj.info.type in {
parser.RObjectType.SPECIAL,
parser.RObjectType.BUILTIN,
}:

value = RBuiltin(name=obj.value.decode("ascii"))

Expand Down Expand Up @@ -854,7 +858,7 @@ def _convert_next(self, data: Union[parser.RData, parser.RObject]) -> Any:


def convert(
data: Union[parser.RData, parser.RObject],
data: parser.RData | parser.RObject,
*args: Any,
**kwargs: Any,
) -> Any:
Expand Down
52 changes: 25 additions & 27 deletions rdata/parser/_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,18 @@
import pathlib
import warnings
import xdrlib
from collections.abc import Iterator
from dataclasses import dataclass
from types import MappingProxyType
from typing import (
Any,
BinaryIO,
Callable,
List,
Final,
Mapping,
Optional,
Sequence,
Set,
TextIO,
Tuple,
)

import numpy as np
Expand All @@ -31,7 +30,6 @@
Traversable as Traversable,
)
except ImportError:
from collections.abc import Iterator
from typing import Protocol, runtime_checkable

@runtime_checkable
Expand Down Expand Up @@ -96,7 +94,7 @@ class FileTypes(enum.Enum):
}


def file_type(data: memoryview) -> Optional[FileTypes]:
def file_type(data: memoryview) -> FileTypes | None:
"""Return the type of the file."""
for filetype, magic in magic_dict.items():
if data[:len(magic)] == magic:
Expand All @@ -112,14 +110,14 @@ class RdataFormats(enum.Enum):
binary = "binary"


format_dict = {
format_dict: Final = MappingProxyType({
RdataFormats.XDR: b"X\n",
RdataFormats.ASCII: b"A\n",
RdataFormats.binary: b"B\n",
}
})


def rdata_format(data: memoryview) -> Optional[RdataFormats]:
def rdata_format(data: memoryview) -> RdataFormats | None:
"""Return the format of the data."""
for format_type, magic in format_dict.items():
if data[:len(magic)] == magic:
Expand Down Expand Up @@ -166,7 +164,7 @@ class RObjectType(enum.Enum):
REF = 255 # Reference


BYTECODE_SPECIAL_SET = frozenset((
BYTECODE_SPECIAL_SET: Final = frozenset((
RObjectType.BCODE,
RObjectType.BCREPREF,
RObjectType.BCREPDEF,
Expand Down Expand Up @@ -224,7 +222,7 @@ class RObjectInfo():
def _str_internal(
obj: RObject | Sequence[RObject],
indent: int = 0,
used_references: Optional[Set[int]] = None,
used_references: Optional[set[int]] = None,
) -> str:

if used_references is None:
Expand Down Expand Up @@ -357,7 +355,7 @@ class EnvironmentValue():

AltRepConstructor = Callable[
[RObject],
Tuple[RObjectInfo, Any],
tuple[RObjectInfo, Any],
]
AltRepConstructorMap = Mapping[bytes, AltRepConstructor]

Expand All @@ -378,7 +376,7 @@ def format_float_with_scipen(number: float, scipen: int) -> bytes:

def deferred_string_constructor(
state: RObject,
) -> Tuple[RObjectInfo, Any]:
) -> tuple[RObjectInfo, Any]:
"""Expand a deferred string ALTREP."""
new_info = RObjectInfo(
type=RObjectType.STR,
Expand Down Expand Up @@ -417,7 +415,7 @@ def compact_seq_constructor(
state: RObject,
*,
is_int: bool = False,
) -> Tuple[RObjectInfo, Any]:
) -> tuple[RObjectInfo, Any]:
"""Expand a compact_seq ALTREP."""
new_info = RObjectInfo(
type=RObjectType.INT if is_int else RObjectType.REAL,
Expand All @@ -444,21 +442,21 @@ def compact_seq_constructor(

def compact_intseq_constructor(
state: RObject,
) -> Tuple[RObjectInfo, Any]:
) -> tuple[RObjectInfo, Any]:
"""Expand a compact_intseq ALTREP."""
return compact_seq_constructor(state, is_int=True)


def compact_realseq_constructor(
state: RObject,
) -> Tuple[RObjectInfo, Any]:
) -> tuple[RObjectInfo, Any]:
"""Expand a compact_realseq ALTREP."""
return compact_seq_constructor(state, is_int=False)


def wrap_constructor(
state: RObject,
) -> Tuple[RObjectInfo, Any]:
) -> tuple[RObjectInfo, Any]:
"""Expand any wrap_* ALTREP."""
new_info = RObjectInfo(
type=state.value[0].info.type,
Expand All @@ -474,7 +472,7 @@ def wrap_constructor(
return new_info, value


default_altrep_map_dict: Mapping[bytes, AltRepConstructor] = {
default_altrep_map_dict: Final[Mapping[bytes, AltRepConstructor]] = {
b"deferred_string": deferred_string_constructor,
b"compact_intseq": compact_intseq_constructor,
b"compact_realseq": compact_realseq_constructor,
Expand All @@ -486,7 +484,7 @@ def wrap_constructor(
b"wrap_raw": wrap_constructor,
}

DEFAULT_ALTREP_MAP = MappingProxyType(default_altrep_map_dict)
DEFAULT_ALTREP_MAP: Final = MappingProxyType(default_altrep_map_dict)


class Parser(abc.ABC):
Expand Down Expand Up @@ -564,7 +562,7 @@ def expand_altrep_to_object(
self,
info: RObject,
state: RObject,
) -> Tuple[RObjectInfo, Any]:
) -> tuple[RObjectInfo, Any]:
"""Expand alternative representation to normal object."""
assert info.info.type == RObjectType.LIST

Expand All @@ -583,8 +581,8 @@ def expand_altrep_to_object(

def _parse_bytecode_constant(
self,
reference_list: Optional[List[RObject]],
bytecode_rep_list: List[RObject | None] | None = None,
reference_list: list[RObject] | None,
bytecode_rep_list: list[RObject | None] | None = None,
) -> RObject:

obj_type = self.parse_int()
Expand All @@ -597,9 +595,9 @@ def _parse_bytecode_constant(

def _parse_bytecode(
self,
reference_list: Optional[List[RObject]],
bytecode_rep_list: List[RObject | None] | None = None,
) -> Tuple[RObject, Sequence[RObject]]:
reference_list: list[RObject] | None,
bytecode_rep_list: list[RObject | None] | None = None,
) -> tuple[RObject, Sequence[RObject]]:
"""Parse R bytecode."""
if bytecode_rep_list is None:
n_repeated = self.parse_int()
Expand All @@ -622,8 +620,8 @@ def _parse_bytecode(

def parse_R_object(
self,
reference_list: List[RObject] | None = None,
bytecode_rep_list: List[RObject | None] | None = None,
reference_list: list[RObject] | None = None,
bytecode_rep_list: list[RObject | None] | None = None,
info_int: int | None = None,
) -> RObject:
"""Parse a R object."""
Expand Down Expand Up @@ -1052,7 +1050,7 @@ def parse_file(

if path is None:
# file is a pre-opened file
buffer: Optional[BinaryIO] = getattr(file_or_path, 'buffer', None)
buffer: BinaryIO | None = getattr(file_or_path, 'buffer', None)
if buffer is None:
assert isinstance(file_or_path, BinaryIO)
binary_file: BinaryIO = file_or_path
Expand Down

0 comments on commit 761a6a8

Please sign in to comment.