Skip to content

Commit ac6fba6

Browse files
List, Dict, Tuple -> list, dict, tuple
1 parent 2f1e3b7 commit ac6fba6

File tree

15 files changed

+55
-72
lines changed

15 files changed

+55
-72
lines changed

src/replit_river/client_transport.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import asyncio
22
import logging
33
from collections.abc import Awaitable, Callable
4-
from typing import Generic, Optional, Tuple
4+
from typing import Generic, Optional
55

66
import websockets
77
from pydantic import ValidationError
@@ -118,7 +118,7 @@ async def _get_existing_session(self) -> Optional[ClientSession]:
118118
async def _establish_new_connection(
119119
self,
120120
old_session: Optional[ClientSession] = None,
121-
) -> Tuple[
121+
) -> tuple[
122122
WebSocketCommonProtocol,
123123
ControlMessageHandshakeRequest[HandshakeMetadataType],
124124
ControlMessageHandshakeResponse,
@@ -292,7 +292,7 @@ async def _establish_handshake(
292292
handshake_metadata: HandshakeMetadataType,
293293
websocket: WebSocketCommonProtocol,
294294
old_session: Optional[ClientSession],
295-
) -> Tuple[
295+
) -> tuple[
296296
ControlMessageHandshakeRequest[HandshakeMetadataType],
297297
ControlMessageHandshakeResponse,
298298
]:

src/replit_river/codegen/client.py

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,12 @@
66
from typing import (
77
Any,
88
Callable,
9-
Dict,
10-
List,
119
Literal,
1210
Optional,
1311
OrderedDict,
1412
Sequence,
1513
Set,
1614
TextIO,
17-
Tuple,
1815
Union,
1916
cast,
2017
)
@@ -78,8 +75,6 @@
7875
import datetime
7976
from typing import (
8077
Any,
81-
Dict,
82-
List,
8378
Literal,
8479
Optional,
8580
Mapping,
@@ -102,19 +97,19 @@
10297

10398
class RiverConcreteType(BaseModel):
10499
type: Optional[str] = Field(default=None)
105-
properties: Dict[str, "RiverType"] = Field(default_factory=lambda: dict())
100+
properties: dict[str, "RiverType"] = Field(default_factory=lambda: dict())
106101
required: Set[str] = Field(default=set())
107102
items: Optional["RiverType"] = Field(default=None)
108103
const: Optional[Union[str, int]] = Field(default=None)
109-
patternProperties: Dict[str, "RiverType"] = Field(default_factory=lambda: dict())
104+
patternProperties: dict[str, "RiverType"] = Field(default_factory=lambda: dict())
110105

111106

112107
class RiverUnionType(BaseModel):
113-
anyOf: List["RiverType"]
108+
anyOf: list["RiverType"]
114109

115110

116111
class RiverIntersectionType(BaseModel):
117-
allOf: List["RiverType"]
112+
allOf: list["RiverType"]
118113

119114

120115
class RiverNotType(BaseModel):
@@ -140,11 +135,11 @@ class RiverProcedure(BaseModel):
140135

141136

142137
class RiverService(BaseModel):
143-
procedures: Dict[str, RiverProcedure]
138+
procedures: dict[str, RiverProcedure]
144139

145140

146141
class RiverSchema(BaseModel):
147-
services: Dict[str, RiverService]
142+
services: dict[str, RiverService]
148143
handshakeSchema: Optional[RiverConcreteType] = Field(default=None)
149144

150145

@@ -166,9 +161,9 @@ def encode_type(
166161
base_model: str,
167162
in_module: list[ModuleName],
168163
permit_unknown_members: bool,
169-
) -> Tuple[TypeExpression, list[ModuleName], list[FileContents], set[TypeName]]:
164+
) -> tuple[TypeExpression, list[ModuleName], list[FileContents], set[TypeName]]:
170165
encoder_name: TypeName | None = None # defining this up here to placate mypy
171-
chunks: List[FileContents] = []
166+
chunks: list[FileContents] = []
172167
if isinstance(type, RiverNotType):
173168
return (NoneTypeExpr(), [], [], set())
174169
elif isinstance(type, RiverUnionType):
@@ -190,7 +185,7 @@ def flatten_union(tpe: RiverType) -> list[RiverType]:
190185

191186
type = RiverUnionType(anyOf=flatten_union(type))
192187

193-
one_of_candidate_types: List[RiverConcreteType] = [
188+
one_of_candidate_types: list[RiverConcreteType] = [
194189
t
195190
for _t in type.anyOf
196191
for t in (_t.anyOf if isinstance(_t, RiverUnionType) else [_t])
@@ -238,7 +233,7 @@ def flatten_union(tpe: RiverType) -> list[RiverType]:
238233
(discriminator_value, []),
239234
)[1].append(oneof_t)
240235

241-
one_of: List[TypeExpression] = []
236+
one_of: list[TypeExpression] = []
242237
if discriminator_name == "$kind":
243238
discriminator_name = "kind"
244239
for pfx, (discriminator_value, oneof_ts) in one_of_pending.items():
@@ -354,7 +349,7 @@ def {_field_name}(
354349
# End of stable union detection
355350
# Restore the non-flattened union type
356351
type = original_type
357-
any_of: List[TypeExpression] = []
352+
any_of: list[TypeExpression] = []
358353

359354
typeddict_encoder = []
360355
for i, t in enumerate(type.anyOf):
@@ -521,7 +516,7 @@ def extract_props(tpe: RiverType) -> list[dict[str, RiverType]]:
521516
return (DictTypeExpr(type_name), module_info, type_chunks, encoder_names)
522517
assert type.type == "object", type.type
523518

524-
current_chunks: List[str] = [
519+
current_chunks: list[str] = [
525520
f"class {render_literal_type(prefix)}({base_model}):"
526521
]
527522
# For the encoder path, do we need "x" to be bound?
@@ -731,7 +726,7 @@ def generate_common_client(
731726
client_name: str,
732727
handshake_type: HandshakeType,
733728
handshake_chunks: Sequence[str],
734-
modules: list[Tuple[ModuleName, ClassName]],
729+
modules: list[tuple[ModuleName, ClassName]],
735730
) -> FileContents:
736731
chunks: list[str] = [ROOT_FILE_HEADER]
737732
chunks.extend(
@@ -763,10 +758,10 @@ def generate_individual_service(
763758
schema_name: str,
764759
schema: RiverService,
765760
input_base_class: Literal["TypedDict"] | Literal["BaseModel"],
766-
) -> Tuple[ModuleName, ClassName, dict[RenderedPath, FileContents]]:
767-
serdes: list[Tuple[list[TypeName], list[ModuleName], list[FileContents]]] = []
761+
) -> tuple[ModuleName, ClassName, dict[RenderedPath, FileContents]]:
762+
serdes: list[tuple[list[TypeName], list[ModuleName], list[FileContents]]] = []
768763
class_name = ClassName(f"{schema_name.title()}Service")
769-
current_chunks: List[str] = [
764+
current_chunks: list[str] = [
770765
dedent(
771766
f"""\
772767
class {class_name}:
@@ -1124,7 +1119,7 @@ def generate_river_client_module(
11241119
else:
11251120
handshake_type = HandshakeType("Literal[None]")
11261121

1127-
modules: list[Tuple[ModuleName, ClassName]] = []
1122+
modules: list[tuple[ModuleName, ClassName]] = []
11281123
input_base_class: Literal["TypedDict"] | Literal["BaseModel"] = (
11291124
"TypedDict" if typed_dict_inputs else "BaseModel"
11301125
)

src/replit_river/codegen/schema.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import json
55
import os.path
66
import tempfile
7-
from typing import Any, DefaultDict, Dict, List
7+
from typing import Any, DefaultDict
88

99
import grpc_tools # type: ignore
1010
from google.protobuf import descriptor_pb2
@@ -29,15 +29,15 @@ def message_type(
2929
module_name: str,
3030
m: descriptor_pb2.DescriptorProto,
3131
sender: bool,
32-
) -> Dict[str, Any]:
32+
) -> dict[str, Any]:
3333
"""Generates the type of a protobuf message into Typebox descriptions."""
34-
type: Dict[str, Any] = {
34+
type: dict[str, Any] = {
3535
"type": "object",
3636
"properties": {},
3737
"required": [],
3838
}
3939
# Non-oneof fields.
40-
oneofs: DefaultDict[int, List[descriptor_pb2.FieldDescriptorProto]] = (
40+
oneofs: DefaultDict[int, list[descriptor_pb2.FieldDescriptorProto]] = (
4141
collections.defaultdict(list)
4242
)
4343
for field in m.field:
@@ -63,11 +63,11 @@ def message_type(
6363
def generate_river_schema(
6464
module_name: str,
6565
fds: descriptor_pb2.FileDescriptorSet,
66-
) -> List[Dict[str, Any]]:
66+
) -> list[dict[str, Any]]:
6767
"""Generates the JSON schema of a River module."""
68-
service_schemas: List[Dict[str, Any]] = []
68+
service_schemas: list[dict[str, Any]] = []
6969

70-
message_types: Dict[str, descriptor_pb2.DescriptorProto] = {}
70+
message_types: dict[str, descriptor_pb2.DescriptorProto] = {}
7171

7272
for pd in fds.file:
7373
for message in pd.message_type:
@@ -80,7 +80,7 @@ def _remove_namespace(name: str) -> str:
8080

8181
# Generate the service stubs.
8282
for service in pd.service:
83-
service_schema: Dict[str, Any] = {
83+
service_schema: dict[str, Any] = {
8484
"name": "".join([service.name[0].lower(), service.name[1:]]),
8585
"state": {},
8686
"procedures": {},

src/replit_river/codegen/server.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import subprocess
44
import tempfile
55
from textwrap import dedent
6-
from typing import DefaultDict, List, Sequence
6+
from typing import DefaultDict, Sequence
77

88
import grpc_tools # type: ignore
99
from google.protobuf import descriptor_pb2
@@ -53,7 +53,7 @@ def _{m.name}Decoder(
5353
),
5454
]
5555
# Non-oneof fields.
56-
oneofs: DefaultDict[int, List[descriptor_pb2.FieldDescriptorProto]] = (
56+
oneofs: DefaultDict[int, list[descriptor_pb2.FieldDescriptorProto]] = (
5757
collections.defaultdict(list)
5858
)
5959
for field in m.field:
@@ -224,13 +224,13 @@ def message_encoder(
224224
f"""\
225225
def _{m.name}Encoder(
226226
e: {module_name}_pb2.{m.name}
227-
) -> Dict[str, Any]:
228-
d: Dict[str, Any] = {{}}
227+
) -> dict[str, Any]:
228+
d: dict[str, Any] = {{}}
229229
"""
230230
),
231231
]
232232
# Non-oneof fields.
233-
oneofs: DefaultDict[int, List[descriptor_pb2.FieldDescriptorProto]] = (
233+
oneofs: DefaultDict[int, list[descriptor_pb2.FieldDescriptorProto]] = (
234234
collections.defaultdict(list)
235235
)
236236
for field in m.field:
@@ -302,12 +302,12 @@ def generate_river_module(
302302
fds: descriptor_pb2.FileDescriptorSet,
303303
) -> Sequence[str]:
304304
"""Generates the lines of a River module."""
305-
chunks: List[str] = [
305+
chunks: list[str] = [
306306
dedent(
307307
f"""\
308308
# Code generated by river.codegen. DO NOT EDIT.
309309
import datetime
310-
from typing import Any, Dict, Mapping, Tuple
310+
from typing import Any, Mapping, Tuple
311311
312312
from google.protobuf import timestamp_pb2
313313
from google.protobuf.wrappers_pb2 import BoolValue
@@ -340,8 +340,8 @@ def add_{service.name}Servicer_to_server(
340340
server: river.Server,
341341
) -> None:
342342
rpc_method_handlers: Mapping[
343-
Tuple[str, str],
344-
Tuple[str, river.GenericRpcHandler]
343+
tuple[str, str],
344+
tuple[str, river.GenericRpcHandler]
345345
] = {{
346346
"""
347347
),

src/replit_river/error_schema.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, List, Optional
1+
from typing import Any, Optional
22

33
from pydantic import BaseModel
44

@@ -91,7 +91,7 @@ def stringify_exception(e: BaseException, limit: int = 10) -> str:
9191
if e.__cause__ is None:
9292
# If there are no causes, just fall back to stringifying the exception.
9393
return str(e)
94-
causes: List[str] = []
94+
causes: list[str] = []
9595
cause: Optional[BaseException] = e
9696
while cause and limit:
9797
causes.append(str(cause))

src/replit_river/rate_limiter.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import asyncio
22
import random
33
from contextvars import Context
4-
from typing import Dict
54

65
from replit_river.transport_options import ConnectionRetryOptions
76

@@ -15,16 +14,16 @@ class LeakyBucketRateLimit:
1514
1615
Attributes:
1716
options (ConnectionRetryOptions): Configuration options for retry behavior.
18-
budget_consumed (Dict[str, int]): Dictionary tracking the number of retries
17+
budget_consumed (dict[str, int]): Dictionary tracking the number of retries
1918
(or budget) consumed per user.
20-
tasks (Dict[str, asyncio.Task]): Dictionary holding asyncio tasks for budget
19+
tasks (dict[str, asyncio.Task]): Dictionary holding asyncio tasks for budget
2120
restoration.
2221
"""
2322

2423
def __init__(self, options: ConnectionRetryOptions):
2524
self.options = options
26-
self.budget_consumed: Dict[str, int] = {}
27-
self.tasks: Dict[str, asyncio.Task] = {}
25+
self.budget_consumed: dict[str, int] = {}
26+
self.tasks: dict[str, asyncio.Task] = {}
2827

2928
def get_backoff_ms(self, user: str) -> float:
3029
"""Calculate the backoff time in milliseconds for a user.

src/replit_river/rpc.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
Awaitable,
77
Callable,
88
Coroutine,
9-
Dict,
109
Generic,
1110
Iterable,
1211
Iterator,
@@ -15,7 +14,6 @@
1514
NoReturn,
1615
Optional,
1716
Sequence,
18-
Tuple,
1917
TypeVar,
2018
Union,
2119
)
@@ -45,7 +43,7 @@
4543
ResponseType = TypeVar("ResponseType")
4644
ErrorType = TypeVar("ErrorType", bound=RiverError)
4745

48-
_MetadataType = Union[grpc.aio.Metadata, Sequence[Tuple[str, Union[str, bytes]]]]
46+
_MetadataType = Union[grpc.aio.Metadata, Sequence[tuple[str, Union[str, bytes]]]]
4947

5048
GenericRpcHandler = Callable[
5149
[str, Channel[Any], Channel[Any]], Coroutine[None, None, None]
@@ -202,7 +200,7 @@ async def write(self, message: ResponseType) -> None:
202200

203201
def get_response_or_error_payload(
204202
response: Any, response_serializer: Callable[[ResponseType], Any]
205-
) -> Dict:
203+
) -> dict[Any, Any]:
206204
if isinstance(response, RiverError):
207205
return {
208206
"ok": False,

src/replit_river/server.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import asyncio
22
import logging
3-
from typing import Mapping, Optional, Tuple
3+
from typing import Mapping, Optional
44

55
import websockets
66
from websockets.exceptions import ConnectionClosed
@@ -35,7 +35,7 @@ async def close(self) -> None:
3535

3636
def add_rpc_handlers(
3737
self,
38-
rpc_handlers: Mapping[Tuple[str, str], Tuple[str, GenericRpcHandler]],
38+
rpc_handlers: Mapping[tuple[str, str], tuple[str, GenericRpcHandler]],
3939
) -> None:
4040
self._transport._handlers.update(rpc_handlers)
4141

src/replit_river/server_transport.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import logging
2-
from typing import Any, Optional, Tuple
2+
from typing import Any, Optional
33

44
import nanoid # type: ignore # type: ignore
55
from pydantic import ValidationError
@@ -192,7 +192,7 @@ async def websocket_closed_callback() -> None:
192192

193193
async def _establish_handshake(
194194
self, request_message: TransportMessage, websocket: WebSocketCommonProtocol
195-
) -> Tuple[
195+
) -> tuple[
196196
ControlMessageHandshakeRequest[Any],
197197
ControlMessageHandshakeResponse,
198198
]:

0 commit comments

Comments
 (0)