Visitar URL original
refactor: `from __future__ import annotations` to simplify typing (#24) · hydrogram/hydrogram@1efdcd5 · GitHub
Skip to content

Commit 1efdcd5

Browse files
authored
refactor: from __future__ import annotations to simplify typing (#24)
1 parent 9b29949 commit 1efdcd5

271 files changed

Lines changed: 2577 additions & 2204 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.pre-commit-config.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ repos:
1111
- id: check-yaml
1212

1313
- repo: https://github.com/astral-sh/ruff-pre-commit
14-
rev: v0.4.4
14+
rev: v0.4.5
1515
hooks:
1616
- id: ruff-format
1717
- id: ruff

‎hydrogram/client.py‎

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@
1717
# You should have received a copy of the GNU Lesser General Public License
1818
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
1919

20+
from __future__ import annotations
21+
2022
import asyncio
2123
import contextlib
2224
import functools
@@ -27,15 +29,14 @@
2729
import re
2830
import shutil
2931
import sys
30-
from collections.abc import AsyncGenerator
3132
from concurrent.futures.thread import ThreadPoolExecutor
3233
from datetime import datetime, timedelta
3334
from hashlib import sha256
3435
from importlib import import_module
3536
from io import BytesIO, StringIO
3637
from mimetypes import MimeTypes
3738
from pathlib import Path
38-
from typing import Callable, Optional, Union
39+
from typing import TYPE_CHECKING, Callable
3940

4041
import hydrogram
4142
from hydrogram import __license__, __version__, enums, raw, utils
@@ -61,6 +62,9 @@
6162
from .parser import Parser
6263
from .session.internals import MsgId
6364

65+
if TYPE_CHECKING:
66+
from collections.abc import AsyncGenerator
67+
6468
log = logging.getLogger(__name__)
6569

6670

@@ -211,28 +215,28 @@ class Client(Methods):
211215
def __init__(
212216
self,
213217
name: str,
214-
api_id: Optional[Union[int, str]] = None,
215-
api_hash: Optional[str] = None,
218+
api_id: int | str | None = None,
219+
api_hash: str | None = None,
216220
app_version: str = APP_VERSION,
217221
device_model: str = DEVICE_MODEL,
218222
system_version: str = SYSTEM_VERSION,
219223
lang_code: str = LANG_CODE,
220224
ipv6: bool = False,
221-
proxy: Optional[dict] = None,
225+
proxy: dict | None = None,
222226
test_mode: bool = False,
223-
bot_token: Optional[str] = None,
224-
session_string: Optional[str] = None,
225-
session_storage_engine: Optional[BaseStorage] = None,
226-
in_memory: Optional[bool] = None,
227-
phone_number: Optional[str] = None,
228-
phone_code: Optional[str] = None,
229-
password: Optional[str] = None,
227+
bot_token: str | None = None,
228+
session_string: str | None = None,
229+
session_storage_engine: BaseStorage | None = None,
230+
in_memory: bool | None = None,
231+
phone_number: str | None = None,
232+
phone_code: str | None = None,
233+
password: str | None = None,
230234
workers: int = WORKERS,
231235
workdir: str = str(WORKDIR),
232-
plugins: Optional[dict] = None,
233-
parse_mode: "enums.ParseMode" = enums.ParseMode.DEFAULT,
234-
no_updates: Optional[bool] = None,
235-
takeout: Optional[bool] = None,
236+
plugins: dict | None = None,
237+
parse_mode: enums.ParseMode = enums.ParseMode.DEFAULT,
238+
no_updates: bool | None = None,
239+
takeout: bool | None = None,
236240
sleep_threshold: int = Session.SLEEP_THRESHOLD,
237241
hide_password: bool = False,
238242
max_concurrent_transmissions: int = MAX_CONCURRENT_TRANSMISSIONS,
@@ -299,7 +303,7 @@ def __init__(
299303

300304
self.disconnect_handler = None
301305

302-
self.me: Optional[User] = None
306+
self.me: User | None = None
303307

304308
self.message_cache = Cache(10000)
305309

@@ -463,7 +467,7 @@ async def authorize(self) -> User:
463467

464468
return signed_up
465469

466-
def set_parse_mode(self, parse_mode: Optional["enums.ParseMode"]):
470+
def set_parse_mode(self, parse_mode: enums.ParseMode | None):
467471
"""Set the parse mode to be used globally by the client.
468472
469473
When setting the parse mode with this method, all other methods having a *parse_mode* parameter will follow the
@@ -502,7 +506,7 @@ def set_parse_mode(self, parse_mode: Optional["enums.ParseMode"]):
502506
self.parse_mode = parse_mode
503507

504508
async def fetch_peers(
505-
self, peers: list[Union[raw.types.User, raw.types.Chat, raw.types.Channel]]
509+
self, peers: list[raw.types.User | raw.types.Chat | raw.types.Channel]
506510
) -> bool:
507511
is_min = False
508512
parsed_peers = []
@@ -884,9 +888,9 @@ async def get_file(
884888
file_size: int = 0,
885889
limit: int = 0,
886890
offset: int = 0,
887-
progress: Optional[Callable] = None,
891+
progress: Callable | None = None,
888892
progress_args: tuple = (),
889-
) -> Optional[AsyncGenerator[bytes, None]]:
893+
) -> AsyncGenerator[bytes, None] | None:
890894
async with self.get_file_semaphore:
891895
file_type = file_id.file_type
892896

@@ -1067,10 +1071,10 @@ async def get_file(
10671071
finally:
10681072
await session.stop()
10691073

1070-
def guess_mime_type(self, filename: str) -> Optional[str]:
1074+
def guess_mime_type(self, filename: str) -> str | None:
10711075
return self.mimetypes.guess_type(filename)[0]
10721076

1073-
def guess_extension(self, mime_type: str) -> Optional[str]:
1077+
def guess_extension(self, mime_type: str) -> str | None:
10741078
return self.mimetypes.guess_extension(mime_type)
10751079

10761080

‎hydrogram/connection/connection.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@
1717
# You should have received a copy of the GNU Lesser General Public License
1818
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
1919

20+
from __future__ import annotations
21+
2022
import asyncio
2123
import logging
22-
from typing import Optional
2324

2425
from hydrogram.session.internals import DataCenter
2526

@@ -72,5 +73,5 @@ async def close(self):
7273
async def send(self, data: bytes):
7374
await self.protocol.send(data)
7475

75-
async def recv(self) -> Optional[bytes]:
76+
async def recv(self) -> bytes | None:
7677
return await self.protocol.recv()

‎hydrogram/connection/transport/tcp/tcp_abridged.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@
1717
# You should have received a copy of the GNU Lesser General Public License
1818
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
1919

20+
from __future__ import annotations
21+
2022
import logging
21-
from typing import Optional
2223

2324
from .tcp import TCP
2425

@@ -40,7 +41,7 @@ async def send(self, data: bytes, *args):
4041
(bytes([length]) if length <= 126 else b"\x7f" + length.to_bytes(3, "little")) + data
4142
)
4243

43-
async def recv(self, length: int = 0) -> Optional[bytes]:
44+
async def recv(self, length: int = 0) -> bytes | None:
4445
length = await super().recv(1)
4546

4647
if length is None:

‎hydrogram/connection/transport/tcp/tcp_abridged_o.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@
1717
# You should have received a copy of the GNU Lesser General Public License
1818
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
1919

20+
from __future__ import annotations
21+
2022
import logging
2123
import os
22-
from typing import Optional
2324

2425
import hydrogram
2526
from hydrogram.crypto import aes
@@ -72,7 +73,7 @@ async def send(self, data: bytes, *args):
7273

7374
await super().send(payload)
7475

75-
async def recv(self, length: int = 0) -> Optional[bytes]:
76+
async def recv(self, length: int = 0) -> bytes | None:
7677
length = await super().recv(1)
7778

7879
if length is None:

‎hydrogram/connection/transport/tcp/tcp_full.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,11 @@
1717
# You should have received a copy of the GNU Lesser General Public License
1818
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
1919

20+
from __future__ import annotations
21+
2022
import logging
2123
from binascii import crc32
2224
from struct import pack, unpack
23-
from typing import Optional
2425

2526
from .tcp import TCP
2627

@@ -44,7 +45,7 @@ async def send(self, data: bytes, *args):
4445

4546
await super().send(data)
4647

47-
async def recv(self, length: int = 0) -> Optional[bytes]:
48+
async def recv(self, length: int = 0) -> bytes | None:
4849
length = await super().recv(4)
4950

5051
if length is None:

‎hydrogram/connection/transport/tcp/tcp_intermediate.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,10 @@
1717
# You should have received a copy of the GNU Lesser General Public License
1818
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
1919

20+
from __future__ import annotations
21+
2022
import logging
2123
from struct import pack, unpack
22-
from typing import Optional
2324

2425
from .tcp import TCP
2526

@@ -37,7 +38,7 @@ async def connect(self, address: tuple):
3738
async def send(self, data: bytes, *args):
3839
await super().send(pack("<i", len(data)) + data)
3940

40-
async def recv(self, length: int = 0) -> Optional[bytes]:
41+
async def recv(self, length: int = 0) -> bytes | None:
4142
length = await super().recv(4)
4243

4344
return None if length is None else await super().recv(unpack("<i", length)[0])

‎hydrogram/connection/transport/tcp/tcp_intermediate_o.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,11 @@
1717
# You should have received a copy of the GNU Lesser General Public License
1818
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
1919

20+
from __future__ import annotations
21+
2022
import logging
2123
import os
2224
from struct import pack, unpack
23-
from typing import Optional
2425

2526
from hydrogram.crypto import aes
2627

@@ -64,7 +65,7 @@ async def connect(self, address: tuple):
6465
async def send(self, data: bytes, *args):
6566
await super().send(aes.ctr256_encrypt(pack("<i", len(data)) + data, *self.encrypt))
6667

67-
async def recv(self, length: int = 0) -> Optional[bytes]:
68+
async def recv(self, length: int = 0) -> bytes | None:
6869
length = await super().recv(4)
6970

7071
if length is None:

‎hydrogram/crypto/aes.py‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@
1717
# You should have received a copy of the GNU Lesser General Public License
1818
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
1919

20+
from __future__ import annotations
21+
2022
import logging
21-
from typing import Optional
2223

2324
log = logging.getLogger(__name__)
2425

@@ -34,12 +35,12 @@ def ige256_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes:
3435
return tgcrypto.ige256_decrypt(data, key, iv)
3536

3637
def ctr256_encrypt(
37-
data: bytes, key: bytes, iv: bytearray, state: Optional[bytearray] = None
38+
data: bytes, key: bytes, iv: bytearray, state: bytearray | None = None
3839
) -> bytes:
3940
return tgcrypto.ctr256_encrypt(data, key, iv, state or bytearray(1))
4041

4142
def ctr256_decrypt(
42-
data: bytes, key: bytes, iv: bytearray, state: Optional[bytearray] = None
43+
data: bytes, key: bytes, iv: bytearray, state: bytearray | None = None
4344
) -> bytes:
4445
return tgcrypto.ctr256_decrypt(data, key, iv, state or bytearray(1))
4546

@@ -65,12 +66,12 @@ def ige256_decrypt(data: bytes, key: bytes, iv: bytes) -> bytes:
6566
return ige(data, key, iv, False)
6667

6768
def ctr256_encrypt(
68-
data: bytes, key: bytes, iv: bytearray, state: Optional[bytearray] = None
69+
data: bytes, key: bytes, iv: bytearray, state: bytearray | None = None
6970
) -> bytes:
7071
return ctr(data, key, iv, state or bytearray(1))
7172

7273
def ctr256_decrypt(
73-
data: bytes, key: bytes, iv: bytearray, state: Optional[bytearray] = None
74+
data: bytes, key: bytes, iv: bytearray, state: bytearray | None = None
7475
) -> bytes:
7576
return ctr(data, key, iv, state or bytearray(1))
7677

‎hydrogram/errors/__init__.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
# You should have received a copy of the GNU Lesser General Public License
1818
# along with Hydrogram. If not, see <http://www.gnu.org/licenses/>.
1919

20-
from typing import ClassVar, Optional
20+
from __future__ import annotations
21+
22+
from typing import ClassVar
2123

2224
from .exceptions import (
2325
AboutTooLong,
@@ -531,14 +533,14 @@ def check(cls, cond: bool, msg: str):
531533
class SecurityCheckMismatch(SecurityError): # noqa: N818
532534
"""Raised when a security check mismatch occurs."""
533535

534-
def __init__(self, msg: Optional[str] = None):
536+
def __init__(self, msg: str | None = None):
535537
super().__init__("A security check mismatch has occurred." if msg is None else msg)
536538

537539

538540
class CDNFileHashMismatch(SecurityError): # noqa: N818
539541
"""Raised when a CDN file hash mismatch occurs."""
540542

541-
def __init__(self, msg: Optional[str] = None):
543+
def __init__(self, msg: str | None = None):
542544
super().__init__("A CDN file hash mismatch has occurred." if msg is None else msg)
543545

544546

0 commit comments

Comments
 (0)