Skip to content

Commit 6fe6664

Browse files
Merge pull request #106 from abn/minor-formatting
Minor non-functional improvements
2 parents 586e28d + 0338fcb commit 6fe6664

File tree

11 files changed

+58
-61
lines changed

11 files changed

+58
-61
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@ output
1414
.idea
1515
.DS_Store
1616
.tox
17+
.venv

betterproto/__init__.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
)
2323

2424
from ._types import T
25-
from .casing import camel_case, safe_snake_case, safe_snake_case, snake_case
25+
from .casing import camel_case, safe_snake_case, snake_case
2626
from .grpc.grpclib_client import ServiceStub
2727

2828
if not (sys.version_info.major == 3 and sys.version_info.minor >= 7):
@@ -378,7 +378,7 @@ def decode_varint(buffer: bytes, pos: int, signed: bool = False) -> Tuple[int, i
378378
result |= (b & 0x7F) << shift
379379
pos += 1
380380
if not (b & 0x80):
381-
return (result, pos)
381+
return result, pos
382382
shift += 7
383383
if shift >= 64:
384384
raise ValueError("Too many bytes when decoding varint.")
@@ -479,15 +479,14 @@ def _get_cls_by_field(cls, fields):
479479
assert meta.map_types
480480
kt = cls._cls_for(field, index=0)
481481
vt = cls._cls_for(field, index=1)
482-
Entry = dataclasses.make_dataclass(
482+
field_cls[field.name] = dataclasses.make_dataclass(
483483
"Entry",
484484
[
485485
("key", kt, dataclass_field(1, meta.map_types[0])),
486486
("value", vt, dataclass_field(2, meta.map_types[1])),
487487
],
488488
bases=(Message,),
489489
)
490-
field_cls[field.name] = Entry
491490
field_cls[field.name + ".value"] = vt
492491
else:
493492
field_cls[field.name] = cls._cls_for(field)
@@ -588,7 +587,7 @@ def __bytes__(self) -> bytes:
588587
serialize_empty = False
589588
if isinstance(value, Message) and value._serialized_on_wire:
590589
# Empty messages can still be sent on the wire if they were
591-
# set (or recieved empty).
590+
# set (or received empty).
592591
serialize_empty = True
593592

594593
if value == self._get_field_default(field_name) and not (
@@ -926,7 +925,7 @@ def which_one_of(message: Message, group_name: str) -> Tuple[str, Any]:
926925

927926

928927
# Circular import workaround: google.protobuf depends on base classes defined above.
929-
from .lib.google.protobuf import (
928+
from .lib.google.protobuf import ( # noqa
930929
Duration,
931930
Timestamp,
932931
BoolValue,

betterproto/_types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
if TYPE_CHECKING:
44
from . import Message
5-
from grpclib._protocols import IProtoMessage
5+
from grpclib._typing import IProtoMessage
66

77
# Bound type variable to allow methods to return `self` of subclasses
88
T = TypeVar("T", bound="Message")

betterproto/grpc/grpclib_client.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import asyncio
33
import grpclib.const
44
from typing import (
5-
Any,
65
AsyncIterable,
76
AsyncIterator,
87
Collection,
@@ -17,8 +16,8 @@
1716
from .._types import ST, T
1817

1918
if TYPE_CHECKING:
20-
from grpclib._protocols import IProtoMessage
21-
from grpclib.client import Channel, Stream
19+
from grpclib._typing import IProtoMessage
20+
from grpclib.client import Channel
2221
from grpclib.metadata import Deadline
2322

2423

betterproto/grpc/util/async_channel.py

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ class ChannelClosed(Exception):
2121

2222
class ChannelDone(Exception):
2323
"""
24-
An exception raised on an attempt to send recieve from a channel that is both closed
24+
An exception raised on an attempt to send receive from a channel that is both closed
2525
and empty.
2626
"""
2727

@@ -32,49 +32,49 @@ class AsyncChannel(AsyncIterable[T]):
3232
"""
3333
A buffered async channel for sending items between coroutines with FIFO ordering.
3434
35-
This makes decoupled bidirection steaming gRPC requests easy if used like:
35+
This makes decoupled bidirectional steaming gRPC requests easy if used like:
3636
3737
.. code-block:: python
3838
client = GeneratedStub(grpclib_chan)
39-
request_chan = await AsyncChannel()
39+
request_channel = await AsyncChannel()
4040
# We can start be sending all the requests we already have
41-
await request_chan.send_from([ReqestObject(...), ReqestObject(...)])
42-
async for response in client.rpc_call(request_chan):
41+
await request_channel.send_from([RequestObject(...), RequestObject(...)])
42+
async for response in client.rpc_call(request_channel):
4343
# The response iterator will remain active until the connection is closed
4444
...
4545
# More items can be sent at any time
46-
await request_chan.send(ReqestObject(...))
46+
await request_channel.send(RequestObject(...))
4747
...
4848
# The channel must be closed to complete the gRPC connection
49-
request_chan.close()
49+
request_channel.close()
5050
5151
Items can be sent through the channel by either:
5252
- providing an iterable to the send_from method
5353
- passing them to the send method one at a time
5454
55-
Items can be recieved from the channel by either:
55+
Items can be received from the channel by either:
5656
- iterating over the channel with a for loop to get all items
57-
- calling the recieve method to get one item at a time
57+
- calling the receive method to get one item at a time
5858
59-
If the channel is empty then recievers will wait until either an item appears or the
59+
If the channel is empty then receivers will wait until either an item appears or the
6060
channel is closed.
6161
6262
Once the channel is closed then subsequent attempt to send through the channel will
6363
fail with a ChannelClosed exception.
6464
65-
When th channel is closed and empty then it is done, and further attempts to recieve
65+
When th channel is closed and empty then it is done, and further attempts to receive
6666
from it will fail with a ChannelDone exception
6767
68-
If multiple coroutines recieve from the channel concurrently, each item sent will be
69-
recieved by only one of the recievers.
68+
If multiple coroutines receive from the channel concurrently, each item sent will be
69+
received by only one of the receivers.
7070
7171
:param source:
7272
An optional iterable will items that should be sent through the channel
7373
immediately.
7474
:param buffer_limit:
7575
Limit the number of items that can be buffered in the channel, A value less than
7676
1 implies no limit. If the channel is full then attempts to send more items will
77-
result in the sender waiting until an item is recieved from the channel.
77+
result in the sender waiting until an item is received from the channel.
7878
:param close:
7979
If set to True then the channel will automatically close after exhausting source
8080
or immediately if no source is provided.
@@ -85,7 +85,7 @@ def __init__(
8585
):
8686
self._queue: asyncio.Queue[Union[T, object]] = asyncio.Queue(buffer_limit)
8787
self._closed = False
88-
self._waiting_recievers: int = 0
88+
self._waiting_receivers: int = 0
8989
# Track whether flush has been invoked so it can only happen once
9090
self._flushed = False
9191

@@ -95,14 +95,14 @@ def __aiter__(self) -> AsyncIterator[T]:
9595
async def __anext__(self) -> T:
9696
if self.done():
9797
raise StopAsyncIteration
98-
self._waiting_recievers += 1
98+
self._waiting_receivers += 1
9999
try:
100100
result = await self._queue.get()
101101
if result is self.__flush:
102102
raise StopAsyncIteration
103103
return result
104104
finally:
105-
self._waiting_recievers -= 1
105+
self._waiting_receivers -= 1
106106
self._queue.task_done()
107107

108108
def closed(self) -> bool:
@@ -116,12 +116,12 @@ def done(self) -> bool:
116116
Check if this channel is done.
117117
118118
:return: True if this channel is closed and and has been drained of items in
119-
which case any further attempts to recieve an item from this channel will raise
119+
which case any further attempts to receive an item from this channel will raise
120120
a ChannelDone exception.
121121
"""
122122
# After close the channel is not yet done until there is at least one waiting
123-
# reciever per enqueued item.
124-
return self._closed and self._queue.qsize() <= self._waiting_recievers
123+
# receiver per enqueued item.
124+
return self._closed and self._queue.qsize() <= self._waiting_receivers
125125

126126
async def send_from(
127127
self, source: Union[Iterable[T], AsyncIterable[T]], close: bool = False
@@ -158,22 +158,22 @@ async def send(self, item: T) -> "AsyncChannel[T]":
158158
await self._queue.put(item)
159159
return self
160160

161-
async def recieve(self) -> Optional[T]:
161+
async def receive(self) -> Optional[T]:
162162
"""
163163
Returns the next item from this channel when it becomes available,
164164
or None if the channel is closed before another item is sent.
165165
:return: An item from the channel
166166
"""
167167
if self.done():
168-
raise ChannelDone("Cannot recieve from a closed channel")
169-
self._waiting_recievers += 1
168+
raise ChannelDone("Cannot receive from a closed channel")
169+
self._waiting_receivers += 1
170170
try:
171171
result = await self._queue.get()
172172
if result is self.__flush:
173173
return None
174174
return result
175175
finally:
176-
self._waiting_recievers -= 1
176+
self._waiting_receivers -= 1
177177
self._queue.task_done()
178178

179179
def close(self):
@@ -190,8 +190,8 @@ async def _flush_queue(self):
190190
"""
191191
if not self._flushed:
192192
self._flushed = True
193-
deadlocked_recievers = max(0, self._waiting_recievers - self._queue.qsize())
194-
for _ in range(deadlocked_recievers):
193+
deadlocked_receivers = max(0, self._waiting_receivers - self._queue.qsize())
194+
for _ in range(deadlocked_receivers):
195195
await self._queue.put(self.__flush)
196196

197197
# A special signal object for flushing the queue when the channel is closed

betterproto/plugin.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def get_py_zero(type_num: int) -> Union[str, float]:
7777
def traverse(proto_file):
7878
def _traverse(path, items, prefix=""):
7979
for i, item in enumerate(items):
80-
# Adjust the name since we flatten the heirarchy.
80+
# Adjust the name since we flatten the hierarchy.
8181
item.name = next_prefix = prefix + item.name
8282
yield item, path + [i]
8383

@@ -355,7 +355,7 @@ def generate_code(request, response):
355355
# Render and then format the output file.
356356
f.content = black.format_str(
357357
template.render(description=output),
358-
mode=black.FileMode(target_versions=set([black.TargetVersion.PY37])),
358+
mode=black.FileMode(target_versions={black.TargetVersion.PY37}),
359359
)
360360

361361
# Make each output directory a package with __init__ file

betterproto/tests/generate.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import os
44
from pathlib import Path
55
import shutil
6-
import subprocess
76
import sys
87
from typing import Set
98

betterproto/tests/grpc/test_grpclib_client.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
DoThingResponse,
44
DoThingRequest,
55
GetThingRequest,
6-
GetThingResponse,
76
TestStub as ThingServiceClient,
87
)
98
import grpclib
@@ -18,14 +17,14 @@ async def _test_client(client, name="clean room", **kwargs):
1817
assert response.names == [name]
1918

2019

21-
def _assert_request_meta_recieved(deadline, metadata):
20+
def _assert_request_meta_received(deadline, metadata):
2221
def server_side_test(stream):
2322
assert stream.deadline._timestamp == pytest.approx(
2423
deadline._timestamp, 1
25-
), "The provided deadline should be recieved serverside"
24+
), "The provided deadline should be received serverside"
2625
assert (
2726
stream.metadata["authorization"] == metadata["authorization"]
28-
), "The provided authorization metadata should be recieved serverside"
27+
), "The provided authorization metadata should be received serverside"
2928

3029
return server_side_test
3130

@@ -42,7 +41,7 @@ async def test_service_call_with_upfront_request_params():
4241
deadline = grpclib.metadata.Deadline.from_timeout(22)
4342
metadata = {"authorization": "12345"}
4443
async with ChannelFor(
45-
[ThingService(test_hook=_assert_request_meta_recieved(deadline, metadata),)]
44+
[ThingService(test_hook=_assert_request_meta_received(deadline, metadata),)]
4645
) as channel:
4746
await _test_client(
4847
ThingServiceClient(channel, deadline=deadline, metadata=metadata)
@@ -53,7 +52,7 @@ async def test_service_call_with_upfront_request_params():
5352
deadline = grpclib.metadata.Deadline.from_timeout(timeout)
5453
metadata = {"authorization": "12345"}
5554
async with ChannelFor(
56-
[ThingService(test_hook=_assert_request_meta_recieved(deadline, metadata),)]
55+
[ThingService(test_hook=_assert_request_meta_received(deadline, metadata),)]
5756
) as channel:
5857
await _test_client(
5958
ThingServiceClient(channel, timeout=timeout, metadata=metadata)
@@ -70,7 +69,7 @@ async def test_service_call_lower_level_with_overrides():
7069
kwarg_deadline = grpclib.metadata.Deadline.from_timeout(28)
7170
kwarg_metadata = {"authorization": "12345"}
7271
async with ChannelFor(
73-
[ThingService(test_hook=_assert_request_meta_recieved(deadline, metadata),)]
72+
[ThingService(test_hook=_assert_request_meta_received(deadline, metadata),)]
7473
) as channel:
7574
client = ThingServiceClient(channel, deadline=deadline, metadata=metadata)
7675
response = await client._unary_unary(
@@ -92,7 +91,7 @@ async def test_service_call_lower_level_with_overrides():
9291
async with ChannelFor(
9392
[
9493
ThingService(
95-
test_hook=_assert_request_meta_recieved(kwarg_deadline, kwarg_metadata),
94+
test_hook=_assert_request_meta_received(kwarg_deadline, kwarg_metadata),
9695
)
9796
]
9897
) as channel:
@@ -140,8 +139,8 @@ async def test_async_gen_for_stream_stream_request():
140139
assert response.version == response_index + 1
141140
response_index += 1
142141
if more_things:
143-
# Send some more requests as we recieve reponses to be sure coordination of
144-
# send/recieve events doesn't matter
142+
# Send some more requests as we receive responses to be sure coordination of
143+
# send/receive events doesn't matter
145144
await request_chan.send(GetThingRequest(more_things.pop(0)))
146145
elif not send_initial_requests.done():
147146
# Make sure the sending task it completed
@@ -151,4 +150,4 @@ async def test_async_gen_for_stream_stream_request():
151150
request_chan.close()
152151
assert response_index == len(
153152
expected_things
154-
), "Didn't recieve all exptected responses"
153+
), "Didn't receive all expected responses"

betterproto/tests/grpc/thing_service.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
DoThingRequest,
44
GetThingRequest,
55
GetThingResponse,
6-
TestStub as ThingServiceClient,
76
)
87
import grpclib
9-
from typing import Any, Dict
8+
import grpclib.server
9+
from typing import Dict
1010

1111

1212
class ThingService:

betterproto/tests/inputs/googletypes_response/test_googletypes_response.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121

2222
@pytest.mark.asyncio
2323
@pytest.mark.parametrize(["service_method", "wrapper_class", "value"], test_cases)
24-
async def test_channel_recieves_wrapped_type(
24+
async def test_channel_receives_wrapped_type(
2525
service_method: Callable[[TestStub], Any], wrapper_class: Callable, value
2626
):
2727
wrapped_value = wrapper_class()

0 commit comments

Comments
 (0)