Skip to content

Commit

Permalink
style: 使用更多 Ruff 静态检查规则优化代码风格
Browse files Browse the repository at this point in the history
  • Loading branch information
FHU-yezi committed Dec 5, 2024
1 parent cc4f831 commit 05e987f
Show file tree
Hide file tree
Showing 15 changed files with 168 additions and 122 deletions.
20 changes: 10 additions & 10 deletions jkit/_base.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from abc import ABCMeta, abstractmethod
from typing import Callable, ClassVar, Optional, TypeVar
from typing import Callable, ClassVar, TypeVar

from msgspec import Struct, convert, to_builtins
from msgspec import ValidationError as MsgspecValidationError
Expand Down Expand Up @@ -67,13 +69,11 @@ def _as_checked(self: P1) -> P1:


class SlugAndUrlMixin:
_slug_check_func: ClassVar[Optional[Callable[[str], bool]]] = None
_slug_to_url_func: ClassVar[Optional[Callable[[str], str]]] = None
_url_to_slug_func: ClassVar[Optional[Callable[[str], str]]] = None
_slug_check_func: ClassVar[Callable[[str], bool] | None] = None
_slug_to_url_func: ClassVar[Callable[[str], str] | None] = None
_url_to_slug_func: ClassVar[Callable[[str], str] | None] = None

def __init__(
self, *, slug: Optional[str] = None, url: Optional[str] = None
) -> None:
def __init__(self, *, slug: str | None = None, url: str | None = None) -> None:
del slug, url

self._slug = ""
Expand Down Expand Up @@ -102,8 +102,8 @@ def _check_params(
cls,
*,
object_readable_name: str,
slug: Optional[str],
url: Optional[str],
slug: str | None,
url: str | None,
) -> str:
# 如果同时提供了 Slug 和 Url
if slug is not None and url is not None:
Expand Down Expand Up @@ -148,7 +148,7 @@ def from_id(cls: type[P3], id: int, /) -> P3: # noqa: A002

@classmethod
@abstractmethod
def from_url(cls: type[P3], url: str, /) -> "P3":
def from_url(cls: type[P3], url: str, /) -> P3:
raise NotImplementedError

@property
Expand Down
18 changes: 10 additions & 8 deletions jkit/_network_request.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import Any, Optional
from __future__ import annotations

from typing import Any

from msgspec.json import Decoder

Expand All @@ -12,8 +14,8 @@ async def get_json(
*,
endpoint: str,
path: str,
params: Optional[dict[str, Any]] = None,
cookies: Optional[dict[str, Any]] = None,
params: dict[str, Any] | None = None,
cookies: dict[str, Any] | None = None,
) -> dict[str, Any]:
response = await HTTP_CLIENT.get(
f"{endpoint}{path}",
Expand All @@ -25,14 +27,14 @@ async def get_json(
return JSON_DECODER.decode(response.content)


async def send_post(
async def send_post( # noqa: PLR0913
*,
endpoint: str,
path: str,
params: Optional[dict[str, Any]] = None,
json: Optional[dict[str, Any]] = None,
headers: Optional[dict[str, Any]] = None,
cookies: Optional[dict[str, Any]] = None,
params: dict[str, Any] | None = None,
json: dict[str, Any] | None = None,
headers: dict[str, Any] | None = None,
cookies: dict[str, Any] | None = None,
) -> dict[str, Any]:
response = await HTTP_CLIENT.post(
f"{endpoint}{path}",
Expand Down
7 changes: 4 additions & 3 deletions jkit/_normalization.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from __future__ import annotations

from datetime import datetime
from decimal import Context, Decimal
from typing import Union


def normalize_datetime(x: Union[int, float, str], /) -> datetime:
def normalize_datetime(x: int | float | str, /) -> datetime:
if isinstance(x, (int, float)):
result = datetime.fromtimestamp(x)
else:
Expand All @@ -20,5 +21,5 @@ def normalize_assets_amount_precise(x: int, /) -> Decimal:
return Context(prec=18).create_decimal_from_float(x / 10**18)


def normalize_percentage(x: Union[int, float], /) -> float:
def normalize_percentage(x: int | float, /) -> float:
return x / 100
25 changes: 15 additions & 10 deletions jkit/article.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

from collections.abc import AsyncGenerator
from datetime import datetime
from enum import Enum
Expand Down Expand Up @@ -58,11 +60,11 @@ class ArticlePaidStatusEnum(Enum):


class PaidInfoField(DataObject, frozen=True):
notebook_paid_status: Optional[NotebookPaidStatusEnum]
notebook_paid_status: NotebookPaidStatusEnum | None
article_paid_status: ArticlePaidStatusEnum
price: Optional[PositiveFloat]
paid_cotent_percent: Optional[Percentage]
paid_readers_count: Optional[NonNegativeInt]
price: PositiveFloat | None
paid_cotent_percent: Percentage | None
paid_readers_count: NonNegativeInt | None


class AuthorInfoField(DataObject, frozen=True):
Expand All @@ -76,7 +78,7 @@ class AuthorInfoField(DataObject, frozen=True):
total_wordage: NonNegativeInt
total_likes_count: NonNegativeInt

def to_user_obj(self) -> "User":
def to_user_obj(self) -> User:
from jkit.user import User

return User.from_slug(self.slug)._as_checked()
Expand Down Expand Up @@ -133,7 +135,7 @@ class ArticleIncludedCollectionInfo(DataObject, frozen=True):
image_url: UserUploadedUrl
owner_name: UserName

def to_collection_obj(self) -> "Collection":
def to_collection_obj(self) -> Collection:
from jkit.collection import Collection

return Collection.from_slug(self.slug)._as_checked()
Expand All @@ -150,7 +152,7 @@ class ArticleBelongToNotebookInfo(DataObject, frozen=True):
id: PositiveInt
name: NonEmptyStr

def to_notebook_obj(self) -> "Notebook":
def to_notebook_obj(self) -> Notebook:
from jkit.notebook import Notebook

return Notebook.from_id(self.id)
Expand All @@ -164,7 +166,7 @@ class CommentPublisherInfoField(DataObject, frozen=True):
address_by_ip: NonEmptyStr

@property
def to_user_obj(self) -> "User":
def to_user_obj(self) -> User:
from jkit.user import User

return User.from_slug(self.slug)._as_checked()
Expand Down Expand Up @@ -206,7 +208,10 @@ class Article(ResourceObject, CheckableMixin, SlugAndUrlMixin):
_url_to_slug_func = article_url_to_slug

def __init__(
self, *, slug: Optional[str] = None, url: Optional[str] = None
self,
*,
slug: str | None = None,
url: Optional[str] = None, # noqa: UP007
) -> None:
super().__init__()

Expand Down Expand Up @@ -313,7 +318,7 @@ async def views_count(self) -> int:
return data["views_count"]

@property
async def audio_info(self) -> Optional[ArticleAudioInfo]:
async def audio_info(self) -> ArticleAudioInfo | None:
await self._auto_check()

data = await get_json(
Expand Down
15 changes: 7 additions & 8 deletions jkit/collection.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from __future__ import annotations

from collections.abc import AsyncGenerator
from typing import (
TYPE_CHECKING,
Any,
Literal,
Optional,
)

from httpx import HTTPStatusError
Expand Down Expand Up @@ -43,7 +44,7 @@ class OwnerInfoField(DataObject, frozen=True):
slug: UserSlug
name: UserName

def to_user_obj(self) -> "User":
def to_user_obj(self) -> User:
from jkit.user import User

return User.from_slug(self.slug)._as_checked()
Expand All @@ -69,7 +70,7 @@ class ArticleAuthorInfoField(DataObject, frozen=True):
name: UserName
avatar_url: UserUploadedUrl

def to_user_obj(self) -> "User":
def to_user_obj(self) -> User:
from jkit.user import User

return User.from_slug(self.slug)._as_checked()
Expand All @@ -80,7 +81,7 @@ class CollectionArticleInfo(DataObject, frozen=True):
slug: ArticleSlug
title: NonEmptyStr
description: str
image_url: Optional[UserUploadedUrl]
image_url: UserUploadedUrl | None
published_at: NormalizedDatetime
is_paid: bool
can_comment: bool
Expand All @@ -92,7 +93,7 @@ class CollectionArticleInfo(DataObject, frozen=True):
tips_count: NonNegativeInt
earned_fp_amount: NonNegativeFloat

def to_article_obj(self) -> "Article":
def to_article_obj(self) -> Article:
from jkit.article import Article

return Article.from_slug(self.slug)._as_checked()
Expand All @@ -103,9 +104,7 @@ class Collection(ResourceObject, CheckableMixin, SlugAndUrlMixin):
_slug_to_url_func = collection_slug_to_url
_url_to_slug_func = collection_url_to_slug

def __init__(
self, *, slug: Optional[str] = None, url: Optional[str] = None
) -> None:
def __init__(self, *, slug: str | None = None, url: str | None = None) -> None:
super().__init__()

self._slug = self._check_params(
Expand Down
6 changes: 4 additions & 2 deletions jkit/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from typing import Literal, Optional, TypeVar
from __future__ import annotations

from typing import Literal, TypeVar

from httpx import AsyncClient
from httpx._types import ProxiesTypes, TimeoutTypes
Expand All @@ -21,7 +23,7 @@ class _NetworkConfig(ConfigObject):
protool: Literal["HTTP/1", "HTTP/2"] = "HTTP/2"

# 代理配置,与 HTTPX proxies 选项支持类型相同
proxies: Optional[ProxiesTypes] = None
proxies: ProxiesTypes | None = None

# 请求超时,与 HTTPX timeout 选项支持类型相同
timeout: TimeoutTypes = 5
Expand Down
6 changes: 4 additions & 2 deletions jkit/jpep/ftn_macket.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from __future__ import annotations

from collections.abc import AsyncGenerator
from enum import Enum
from typing import Literal, Optional
from typing import Literal

from jkit._base import DataObject, ResourceObject
from jkit._network_request import send_post
Expand All @@ -25,7 +27,7 @@ class PublisherInfoField(DataObject, frozen=True):
id: PositiveInt
name: NonEmptyStr
hashed_name: NonEmptyStr
avatar_url: Optional[NonEmptyStr]
avatar_url: NonEmptyStr | None
credit: NonNegativeInt


Expand Down
12 changes: 7 additions & 5 deletions jkit/notebook.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from collections.abc import AsyncGenerator
from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar
from typing import TYPE_CHECKING, Any, Literal, TypeVar

from httpx import HTTPStatusError

Expand Down Expand Up @@ -40,7 +42,7 @@ class AuthorInfoField(DataObject, frozen=True):
name: UserName
avatar_url: UserUploadedUrl

def to_user_obj(self) -> "User":
def to_user_obj(self) -> User:
from jkit.user import User

return User.from_slug(self.slug)._as_checked()
Expand All @@ -63,7 +65,7 @@ class ArticleAuthorInfoField(DataObject, frozen=True):
name: UserName
avatar_url: UserUploadedUrl

def to_user_obj(self) -> "User":
def to_user_obj(self) -> User:
from jkit.user import User

return User.from_slug(self.slug)._as_checked()
Expand All @@ -74,7 +76,7 @@ class NotebookArticleInfo(DataObject, frozen=True):
slug: ArticleSlug
title: NonEmptyStr
description: str
image_url: Optional[UserUploadedUrl]
image_url: UserUploadedUrl | None
published_at: NormalizedDatetime
is_paid: bool
can_comment: bool
Expand All @@ -86,7 +88,7 @@ class NotebookArticleInfo(DataObject, frozen=True):
tips_count: NonNegativeInt
earned_fp_amount: NonNegativeFloat

def to_article_obj(self) -> "Article":
def to_article_obj(self) -> Article:
from jkit.article import Article

return Article.from_slug(self.slug)._as_checked()
Expand Down
11 changes: 6 additions & 5 deletions jkit/private/assets.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from __future__ import annotations

from collections.abc import AsyncGenerator
from contextlib import suppress
from datetime import datetime
from decimal import Decimal
from typing import Optional, Union

from httpx import HTTPStatusError
from msgspec import DecodeError
Expand Down Expand Up @@ -87,7 +88,7 @@ def __init__(self, *, credential: JianshuCredential) -> None:
self._credential = credential

async def iter_fp_records(
self, *, max_id: Optional[int] = None
self, *, max_id: int | None = None
) -> AsyncGenerator[AssetsTransactionRecord, None]:
now_max_id = max_id

Expand Down Expand Up @@ -120,7 +121,7 @@ async def iter_fp_records(
)._validate()

async def iter_ftn_records(
self, *, max_id: Optional[int] = None
self, *, max_id: int | None = None
) -> AsyncGenerator[AssetsTransactionRecord, None]:
now_max_id = max_id

Expand Down Expand Up @@ -279,7 +280,7 @@ async def iter_expired_benefit_cards(

now_page += 1

async def fp_to_ftn(self, /, amount: Union[int, float]) -> None:
async def fp_to_ftn(self, /, amount: int | float) -> None:
if amount <= 0:
raise ValueError("转换的简书钻数量必须大于 0")

Expand All @@ -305,7 +306,7 @@ async def fp_to_ftn(self, /, amount: Union[int, float]) -> None:

raise e from None

async def ftn_to_fp(self, /, amount: Union[int, float]) -> None:
async def ftn_to_fp(self, /, amount: int | float) -> None:
if amount <= 0:
raise ValueError("转换的简书贝数量必须大于 0")

Expand Down
Loading

0 comments on commit 05e987f

Please sign in to comment.