Skip to content

Commit

Permalink
chore: ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
BlueGlassBlock committed Nov 16, 2024
1 parent 027786f commit 931455e
Show file tree
Hide file tree
Showing 18 changed files with 206 additions and 183 deletions.
2 changes: 1 addition & 1 deletion kayaku/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .manager import Kayaku
from .manager import Kayaku as Kayaku
from .utils import copying_field

default = copying_field
3 changes: 2 additions & 1 deletion kayaku/backend/encode.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

from typing import Any, Callable, TextIO
from collections.abc import Callable
from typing import Any, TextIO

from . import wsc
from .types import AnyNumber, Float, Identifier, Integer, JNumber, JString, JWrapper
Expand Down
4 changes: 1 addition & 3 deletions kayaku/backend/transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,7 @@ def object(self, children: list) -> Any:
return o

def array(self, children: list) -> Any:
a = Array(
(cast(Value, value) for value in children if isinstance(value, JType))
)
a = Array(cast(Value, value) for value in children if isinstance(value, JType))
self._set_trail(a, children)
return a

Expand Down
20 changes: 9 additions & 11 deletions kayaku/backend/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@
import re
from datetime import date, datetime, time
from enum import Enum
from typing import TYPE_CHECKING, Any, Generic, List, Tuple, TypeVar, overload

from typing_extensions import Self, TypeAlias
from typing import TYPE_CHECKING, Any, Generic, Self, TypeAlias, TypeVar, overload


class JType:
Expand All @@ -32,7 +30,7 @@ def __post_init__(self) -> Self:
return self

def __repr__(self) -> str:
if attrs := getattr(self, "__dict__"):
if attrs := self.__dict__:
kwargs = ", ".join(f"{k}={v}" for k, v in attrs.items())
return f"{self.__class__.__name__}({super().__repr__()}, {kwargs})"
return f"{self.__class__.__name__}({super().__repr__()})"
Expand Down Expand Up @@ -97,15 +95,15 @@ class JObject(JContainer, dict):
T = TypeVar("T")


class Array(JContainer, List[T]):
class Array(JContainer, list[T]):
"""A JSON Array with style preservation"""


class Identifier(JType, str):
"A quoteless string without special characters"

def __repr__(self) -> str:
if attrs := getattr(self, "__dict__"):
if attrs := self.__dict__:
kwargs = ", ".join(f"{k}={v}" for k, v in attrs.items())
return f"{self.__class__.__name__}({super().__repr__()}, {kwargs})"
return f"{self.__class__.__name__}({super().__repr__()})"
Expand Down Expand Up @@ -141,7 +139,7 @@ def __post_init__(
return self

def __repr__(self) -> str:
if attrs := getattr(self, "__dict__"):
if attrs := self.__dict__:
kwargs = ", ".join(f"{k}={v}" for k, v in attrs.items())
return f"{self.__class__.__name__}({self.quote.value}{self}{self.quote.value}, {kwargs})"
return f"{self.__class__.__name__}({super().__repr__()})"
Expand Down Expand Up @@ -262,7 +260,7 @@ def __round_dump__(self) -> str:
A type alias matching the JSON Value.
"""

Member = Tuple[Key, Value]
Member = tuple[Key, Value]
"""
A Key-Value pair in an [Object][kayaku.backend.types.Object]
"""
Expand Down Expand Up @@ -310,11 +308,11 @@ def convert(obj: Any) -> JType: ...
def convert(obj: Any) -> JType:
if isinstance(obj, JType):
return obj
if isinstance(obj, (list, tuple)):
if isinstance(obj, list | tuple):
o = Array(obj)
elif (
isinstance(obj, (bool, date, time, datetime, re.Pattern, enum.Enum))
or obj == None
isinstance(obj, bool | date | time | datetime | re.Pattern | enum.Enum)
or obj is None
):
o = JWrapper(obj)
elif isinstance(obj, dict):
Expand Down
9 changes: 6 additions & 3 deletions kayaku/bi_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,12 @@ def insert(self, frags: Iterable[str]) -> Suffix:
def lookup(
self, frags: Sequence[str], index: int = 0
) -> tuple[tuple[SourceSpec, PathSpec], DestWithMount] | None:
if index < len(frags) and (nxt_nd := self.nxt.get(frags[index], None)):
if lookup_res := nxt_nd.lookup(frags, index + 1):
return lookup_res
if (
index < len(frags)
and (nxt_nd := self.nxt.get(frags[index], None))
and (lookup_res := nxt_nd.lookup(frags, index + 1))
):
return lookup_res
if self.suffix:
suffix_ind, spec = self.suffix.lookup(reversed(frags[index:]))
if spec:
Expand Down
6 changes: 3 additions & 3 deletions kayaku/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import inspect
from dataclasses import MISSING, Field, asdict, is_dataclass
from typing import Union, cast
from typing import cast

from .backend.types import Array, BlockStyleComment, JObject, JString, JType, convert
from .schema_gen import DataClass
Expand All @@ -11,7 +11,7 @@
def remove_generated_comment(obj: JType):
obj.json_before = [wsc for wsc in obj.json_before if "@type" not in wsc]
obj.json_after = [wsc for wsc in obj.json_after if "@type" not in wsc]
if isinstance(obj, (JObject, Array)):
if isinstance(obj, JObject | Array):
obj.json_container_tail = [
wsc for wsc in obj.json_container_tail if "@type" not in wsc
]
Expand Down Expand Up @@ -63,7 +63,7 @@ def format_with_model(container: JObject, model: type[DataClass]) -> None:
raise TypeError(f"{container} is not a json object.")

fields = {
k: (f, cast(Union[str, None], f.metadata.get("description")))
k: (f, cast(str | None, f.metadata.get("description")))
for k, f in model.__dataclass_fields__.items()
}
format_exist(fields, container)
Expand Down
8 changes: 4 additions & 4 deletions kayaku/manager.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from collections.abc import Sequence
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from dataclasses import fields as get_fields
from pathlib import Path
from typing import Any, Callable, Literal, TypeAlias, TypeVar, overload
from typing import Any, Literal, TypeAlias, TypeVar, overload

from .backend import dumps, loads
from .backend.types import JObject, Quote
Expand Down Expand Up @@ -77,8 +77,8 @@ def register(self, domain: DomainIdent, cls: type[DataClass]) -> Path:
file_store = self.files.setdefault(
path, _FileEntry(self.get_schema_generator(None))
)
for field in get_fields(cls):
sub_dest: MountIdent = mount + (field.name,)
for dc_field in get_fields(cls):
sub_dest: MountIdent = mount + (dc_field.name,)
if sub_dest in file_store.mount_record:
raise NameError(
f"{path.with_suffix('').as_posix()}::{'.'.join(sub_dest)} is occupied!"
Expand Down
8 changes: 4 additions & 4 deletions kayaku/pretty.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def prettify_object(self, obj: JObject) -> JObject:
k, v = self.convert_key(k), convert(v)
sub_comments = self.collect_comments(k) + self.collect_comments(v)
if not (
sub_comments or (v and isinstance(v, (list, tuple, dict)))
sub_comments or (v and isinstance(v, list | tuple | dict))
): # is simple type
k.__json_clear__()
v.__json_clear__()
Expand All @@ -177,7 +177,7 @@ def prettify_object(self, obj: JObject) -> JObject:
newline = self.require_newline(k.json_before)
k.__json_clear__()
v.__json_clear__()
if isinstance(v, (Array, JObject)):
if isinstance(v, Array | JObject):
v = self.prettify(v)
v.json_before.append(WhiteSpace(" "))
new_obj[k] = v
Expand All @@ -194,7 +194,7 @@ def prettify_array(self, arr: Array) -> Array:
v: JType = convert(arr[0])
sub_comments = self.collect_comments(v)
if not (
sub_comments or (v and isinstance(v, (list, tuple, dict)))
sub_comments or (v and isinstance(v, list | tuple | dict))
): # is simple type
v.__json_clear__()
return Array((v,)).__post_init__()
Expand All @@ -210,7 +210,7 @@ def prettify_array(self, arr: Array) -> Array:
sub_comments = self.collect_comments(v)
newline = self.require_newline(v.json_before)
v.__json_clear__()
if isinstance(v, (Array, JObject)):
if isinstance(v, Array | JObject):
v = self.prettify(v)
v.json_before = self.format_wsc(sub_comments, newline)
new_arr.append(v)
Expand Down
Loading

0 comments on commit 931455e

Please sign in to comment.