Skip to content

Commit

Permalink
PyUpgrade unsafe fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
seriaati committed Sep 22, 2024
1 parent 8e03101 commit 39597d6
Show file tree
Hide file tree
Showing 52 changed files with 311 additions and 312 deletions.
8 changes: 4 additions & 4 deletions genshin-dev/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
import setuptools


def parse_requirements_file(path: pathlib.Path) -> typing.List[str]:
def parse_requirements_file(path: pathlib.Path) -> list[str]:
"""Parse a requirements file into a list of requirements."""
with open(path) as fp:
raw_dependencies = fp.readlines()

dependencies: typing.List[str] = []
dependencies: list[str] = []
for dependency in raw_dependencies:
comment_index = dependency.find("#")
if comment_index == 0:
Expand All @@ -30,8 +30,8 @@ def parse_requirements_file(path: pathlib.Path) -> typing.List[str]:

normal_requirements = parse_requirements_file(dev_directory / ".." / "requirements.txt")

all_extras: typing.Set[str] = set()
extras: typing.Dict[str, typing.Sequence[str]] = {}
all_extras: set[str] = set()
extras: dict[str, typing.Sequence[str]] = {}

for path in dev_directory.glob("*-requirements.txt"):
name = path.name.split("-")[0]
Expand Down
2 changes: 1 addition & 1 deletion genshin/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ async def honkai_stats(client: genshin.Client, uid: int) -> None:
for k, v in data.stats.model_dump().items():
if isinstance(v, dict):
click.echo(f"{k}:")
for nested_k, nested_v in typing.cast("typing.Dict[str, object]", v).items():
for nested_k, nested_v in typing.cast("dict[str, object]", v).items():
click.echo(f" {nested_k}: {click.style(str(nested_v), bold=True)}")
else:
click.echo(f"{k}: {click.style(str(v), bold=True)}")
Expand Down
22 changes: 11 additions & 11 deletions genshin/client/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

def _separate(values: typing.Iterable[typing.Any], sep: str = ":") -> str:
"""Separate a sequence by a separator into a single string."""
parts: typing.List[str] = []
parts: list[str] = []
for value in values:
if value is None:
parts.append("null")
Expand Down Expand Up @@ -64,15 +64,15 @@ class BaseCache(abc.ABC):
"""Base cache for the client."""

@abc.abstractmethod
async def get(self, key: typing.Any) -> typing.Optional[typing.Any]:
async def get(self, key: typing.Any) -> typing.Any | None:
"""Get an object with a key."""

@abc.abstractmethod
async def set(self, key: typing.Any, value: typing.Any) -> None:
"""Save an object with a key."""

@abc.abstractmethod
async def get_static(self, key: typing.Any) -> typing.Optional[typing.Any]:
async def get_static(self, key: typing.Any) -> typing.Any | None:
"""Get a static object with a key."""

@abc.abstractmethod
Expand All @@ -83,7 +83,7 @@ async def set_static(self, key: typing.Any, value: typing.Any) -> None:
class Cache(BaseCache):
"""Standard implementation of the cache."""

cache: typing.Dict[typing.Any, typing.Tuple[float, typing.Any]]
cache: dict[typing.Any, tuple[float, typing.Any]]
maxsize: int
ttl: float
static_ttl: float
Expand Down Expand Up @@ -115,7 +115,7 @@ def _clear_cache(self) -> None:
for key in keys:
del self.cache[key]

async def get(self, key: typing.Any) -> typing.Optional[typing.Any]:
async def get(self, key: typing.Any) -> typing.Any | None:
"""Get an object with a key."""
self._clear_cache()

Expand All @@ -130,7 +130,7 @@ async def set(self, key: typing.Any, value: typing.Any) -> None:

self._clear_cache()

async def get_static(self, key: typing.Any) -> typing.Optional[typing.Any]:
async def get_static(self, key: typing.Any) -> typing.Any | None:
"""Get a static object with a key."""
return await self.get(key)

Expand Down Expand Up @@ -167,15 +167,15 @@ def serialize_key(self, key: typing.Any) -> str:
"""Serialize a key by turning it into a string."""
return str(key)

def serialize_value(self, value: typing.Any) -> typing.Union[str, bytes]:
def serialize_value(self, value: typing.Any) -> str | bytes:
"""Serialize a value by turning it into bytes."""
return json.dumps(value)

def deserialize_value(self, value: bytes) -> typing.Any:
"""Deserialize a value back into data."""
return json.loads(value)

async def get(self, key: typing.Any) -> typing.Optional[typing.Any]:
async def get(self, key: typing.Any) -> typing.Any | None:
"""Get an object with a key."""
value = typing.cast("typing.Optional[bytes]", await self.redis.get(self.serialize_key(key))) # pyright: ignore
if value is None:
Expand All @@ -191,7 +191,7 @@ async def set(self, key: typing.Any, value: typing.Any) -> None:
ex=self.ttl,
)

async def get_static(self, key: typing.Any) -> typing.Optional[typing.Any]:
async def get_static(self, key: typing.Any) -> typing.Any | None:
"""Get a static object with a key."""
return await self.get(key)

Expand Down Expand Up @@ -258,7 +258,7 @@ def deserialize_value(self, value: str) -> typing.Any:
"""Deserialize a value back into data."""
return json.loads(value)

async def get(self, key: typing.Any) -> typing.Optional[typing.Any]:
async def get(self, key: typing.Any) -> typing.Any | None:
"""Get an object with a key."""
import aiosqlite

Expand Down Expand Up @@ -299,7 +299,7 @@ async def set(self, key: typing.Any, value: typing.Any) -> None:
if self.conn is None:
await conn.close()

async def get_static(self, key: typing.Any) -> typing.Optional[typing.Any]:
async def get_static(self, key: typing.Any) -> typing.Any | None:
"""Get a static object with a key."""
return await self.get(key)

Expand Down
22 changes: 11 additions & 11 deletions genshin/client/compatibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ class GenshinClient(clients.Client):

def __init__(
self,
cookies: typing.Optional[typing.Any] = None,
authkey: typing.Optional[str] = None,
cookies: typing.Any | None = None,
authkey: str | None = None,
*,
lang: str = "en-us",
region: types.Region = types.Region.OVERSEAS,
Expand Down Expand Up @@ -59,7 +59,7 @@ def cookies(self, cookies: typing.Mapping[str, typing.Any]) -> None:
setattr(self.cookie_manager, "cookies", cookies)

@property
def uid(self) -> typing.Optional[int]:
def uid(self) -> int | None:
deprecation.warn_deprecated(self.__class__.uid, alternative="Client.uids[genshin.Game.GENSHIN]")
return self.uids[types.Game.GENSHIN]

Expand All @@ -83,7 +83,7 @@ async def get_partial_user(
self,
uid: int,
*,
lang: typing.Optional[str] = None,
lang: str | None = None,
) -> models.PartialGenshinUserStats:
"""Get partial genshin user without character equipment."""
return await self.get_partial_genshin_user(uid, lang=lang)
Expand All @@ -93,7 +93,7 @@ async def get_characters(
self,
uid: int,
*,
lang: typing.Optional[str] = None,
lang: str | None = None,
) -> typing.Sequence[models.Character]:
"""Get genshin user characters."""
return await self.get_genshin_characters(uid, lang=lang)
Expand All @@ -103,7 +103,7 @@ async def get_user(
self,
uid: int,
*,
lang: typing.Optional[str] = None,
lang: str | None = None,
) -> models.GenshinUserStats:
"""Get genshin user."""
return await self.get_genshin_user(uid, lang=lang)
Expand All @@ -113,7 +113,7 @@ async def get_full_user(
self,
uid: int,
*,
lang: typing.Optional[str] = None,
lang: str | None = None,
) -> models.FullGenshinUserStats:
"""Get a user with all their possible data."""
return await self.get_full_genshin_user(uid, lang=lang)
Expand All @@ -129,8 +129,8 @@ class ChineseClient(GenshinClient):

def __init__(
self,
cookies: typing.Optional[typing.Mapping[str, str]] = None,
authkey: typing.Optional[str] = None,
cookies: typing.Mapping[str, str] | None = None,
authkey: str | None = None,
*,
lang: str = "zh-cn",
debug: bool = False,
Expand All @@ -154,7 +154,7 @@ class MultiCookieClient(GenshinClient):

def __init__(
self,
cookie_list: typing.Optional[typing.Sequence[typing.Mapping[str, str]]] = None,
cookie_list: typing.Sequence[typing.Mapping[str, str]] | None = None,
*,
lang: str = "en-us",
debug: bool = False,
Expand All @@ -176,7 +176,7 @@ class ChineseMultiCookieClient(GenshinClient):

def __init__(
self,
cookie_list: typing.Optional[typing.Sequence[typing.Mapping[str, str]]] = None,
cookie_list: typing.Sequence[typing.Mapping[str, str]] | None = None,
*,
lang: str = "en-us",
debug: bool = False,
Expand Down
18 changes: 9 additions & 9 deletions genshin/client/components/auth/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

__all__ = ["PAGES", "enter_code", "launch_webapp", "solve_geetest"]

PAGES: typing.Final[typing.Dict[typing.Literal["captcha", "enter-code"], str]] = {
PAGES: typing.Final[dict[typing.Literal["captcha", "enter-code"], str]] = {
"captcha": """
<!DOCTYPE html>
<head>
Expand Down Expand Up @@ -112,11 +112,11 @@
async def launch_webapp(
page: typing.Literal["captcha"],
*,
mmt: typing.Union[MMT, MMTv4, SessionMMT, SessionMMTv4, RiskyCheckMMT],
mmt: MMT | MMTv4 | SessionMMT | SessionMMTv4 | RiskyCheckMMT,
lang: str = ...,
api_server: str = ...,
port: int = ...,
) -> typing.Union[MMTResult, MMTv4Result, SessionMMTResult, SessionMMTv4Result, RiskyCheckMMTResult]: ...
) -> MMTResult | MMTv4Result | SessionMMTResult | SessionMMTv4Result | RiskyCheckMMTResult: ...
@typing.overload
async def launch_webapp(
page: typing.Literal["enter-code"],
Expand All @@ -129,11 +129,11 @@ async def launch_webapp(
async def launch_webapp(
page: typing.Literal["captcha", "enter-code"],
*,
mmt: typing.Optional[typing.Union[MMT, MMTv4, SessionMMT, SessionMMTv4, RiskyCheckMMT]] = None,
lang: typing.Optional[str] = None,
api_server: typing.Optional[str] = None,
mmt: MMT | MMTv4 | SessionMMT | SessionMMTv4 | RiskyCheckMMT | None = None,
lang: str | None = None,
api_server: str | None = None,
port: int = 5000,
) -> typing.Union[MMTResult, MMTv4Result, SessionMMTResult, SessionMMTv4Result, RiskyCheckMMTResult, str]:
) -> MMTResult | MMTv4Result | SessionMMTResult | SessionMMTv4Result | RiskyCheckMMTResult | str:
"""Create and run a webapp to solve captcha or enter a verification code."""
routes = web.RouteTableDef()
future: asyncio.Future[typing.Any] = asyncio.Future()
Expand Down Expand Up @@ -244,12 +244,12 @@ async def solve_geetest(
port: int = ...,
) -> MMTv4Result: ...
async def solve_geetest(
mmt: typing.Union[MMT, MMTv4, SessionMMT, SessionMMTv4, RiskyCheckMMT],
mmt: MMT | MMTv4 | SessionMMT | SessionMMTv4 | RiskyCheckMMT,
*,
lang: str = "en-us",
api_server: str = "api-na.geetest.com",
port: int = 5000,
) -> typing.Union[MMTResult, MMTv4Result, SessionMMTResult, SessionMMTv4Result, RiskyCheckMMTResult]:
) -> MMTResult | MMTv4Result | SessionMMTResult | SessionMMTv4Result | RiskyCheckMMTResult:
"""Start a web server and manually solve geetest captcha."""
lang = auth_utility.lang_to_geetest_lang(lang)
return await launch_webapp(
Expand Down
2 changes: 1 addition & 1 deletion genshin/client/components/auth/subclients/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ async def _create_qrcode(self) -> QRCodeCreationResult:
url=data["data"]["url"],
)

async def _check_qrcode(self, ticket: str) -> typing.Tuple[QRCodeStatus, SimpleCookie]:
async def _check_qrcode(self, ticket: str) -> tuple[QRCodeStatus, SimpleCookie]:
"""Check the status of a QR code login."""
payload = {"ticket": ticket}

Expand Down
10 changes: 5 additions & 5 deletions genshin/client/components/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ class BaseClient(abc.ABC):
_region: types.Region
_default_game: typing.Optional[types.Game]

uids: typing.Dict[types.Game, int]
authkeys: typing.Dict[types.Game, str]
uids: dict[types.Game, int]
authkeys: dict[types.Game, str]
_hoyolab_id: typing.Optional[int]
_accounts: typing.Dict[types.Game, hoyolab_models.GenshinAccount]
_accounts: dict[types.Game, hoyolab_models.GenshinAccount]
custom_headers: multidict.CIMultiDict[str]

def __init__(
Expand Down Expand Up @@ -500,7 +500,7 @@ async def _update_cached_uids(self) -> None:
"""Update cached fallback uids."""
mixed_accounts = await self.get_game_accounts()

game_accounts: typing.Dict[types.Game, typing.List[hoyolab_models.GenshinAccount]] = {}
game_accounts: dict[types.Game, list[hoyolab_models.GenshinAccount]] = {}
for account in mixed_accounts:
if not isinstance(account.game, types.Game): # pyright: ignore[reportUnnecessaryIsInstance]
continue
Expand Down Expand Up @@ -533,7 +533,7 @@ async def _update_cached_accounts(self) -> None:
"""Update cached fallback accounts."""
mixed_accounts = await self.get_game_accounts()

game_accounts: typing.Dict[types.Game, typing.List[hoyolab_models.GenshinAccount]] = {}
game_accounts: dict[types.Game, list[hoyolab_models.GenshinAccount]] = {}
for account in mixed_accounts:
if not isinstance(account.game, types.Game): # pyright: ignore[reportUnnecessaryIsInstance]
continue
Expand Down
Loading

0 comments on commit 39597d6

Please sign in to comment.