Skip to content

Commit 192ccc5

Browse files
authored
feat: enable mypy session for ndb (googleapis#16691)
This PR enables the mypy session in noxfile.py for ndb and aligns it with the GAPIC generator template.
1 parent 399d90b commit 192ccc5

21 files changed

Lines changed: 291 additions & 142 deletions

‎packages/google-cloud-ndb/google/cloud/ndb/__init__.py‎

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

2424
fromgoogle.cloud.ndbimportversion
2525

26-
__version__=version.__version__
26+
__version__: str=version.__version__
2727

2828
fromgoogle.cloud.ndb.clientimportClient
2929
fromgoogle.cloud.ndb.contextimportAutoBatcher

‎packages/google-cloud-ndb/google/cloud/ndb/_cache.py‎

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -117,18 +117,18 @@ def done_callback(self, cache_call):
117117
"""
118118
exception=cache_call.exception()
119119
ifexception:
120-
forfutureinself.futures:
120+
forfutureinself.futures:# type: ignore[attr-defined]
121121
future.set_exception(exception)
122122

123123
else:
124-
forfutureinself.futures:
124+
forfutureinself.futures:# type: ignore[attr-defined]
125125
future.set_result(None)
126126

127127
defmake_call(self):
128128
"""Make the actual call to the global cache. To be overridden."""
129129
raiseNotImplementedError
130130

131-
deffuture_info(self, key):
131+
deffuture_info(self, key, value=None):
132132
"""Generate info string for Future. To be overridden."""
133133
raiseNotImplementedError
134134

@@ -279,7 +279,7 @@ def make_call(self):
279279
"""Call :method:`GlobalCache.get`."""
280280
return_global_cache().get(self.keys)
281281

282-
deffuture_info(self, key):
282+
deffuture_info(self, key, value=None):
283283
"""Generate info string for Future."""
284284
return"GlobalCache.get({})".format(key)
285285

@@ -373,7 +373,7 @@ def make_call(self):
373373
"""Call :method:`GlobalCache.set`."""
374374
return_global_cache().set(self.todo, expires=self.expires)
375375

376-
deffuture_info(self, key, value):
376+
deffuture_info(self, key, value=None):
377377
"""Generate info string for Future."""
378378
return"GlobalCache.set({}, {})".format(key, value)
379379

@@ -436,7 +436,7 @@ def make_call(self):
436436
"""Call :method:`GlobalCache.set`."""
437437
return_global_cache().set_if_not_exists(self.todo, expires=self.expires)
438438

439-
deffuture_info(self, key, value):
439+
deffuture_info(self, key, value=None):
440440
"""Generate info string for Future."""
441441
return"GlobalCache.set_if_not_exists({}, {})".format(key, value)
442442

@@ -482,7 +482,7 @@ def make_call(self):
482482
"""Call :method:`GlobalCache.delete`."""
483483
return_global_cache().delete(self.keys)
484484

485-
deffuture_info(self, key):
485+
deffuture_info(self, key, value=None):
486486
"""Generate info string for Future."""
487487
return"GlobalCache.delete({})".format(key)
488488

@@ -513,7 +513,7 @@ def make_call(self):
513513
"""Call :method:`GlobalCache.watch`."""
514514
return_global_cache().watch(self.todo)
515515

516-
deffuture_info(self, key, value):
516+
deffuture_info(self, key, value=None):
517517
"""Generate info string for Future."""
518518
return"GlobalCache.watch({}, {})".format(key, value)
519519

@@ -543,7 +543,7 @@ def make_call(self):
543543
"""Call :method:`GlobalCache.unwatch`."""
544544
return_global_cache().unwatch(self.keys)
545545

546-
deffuture_info(self, key):
546+
deffuture_info(self, key, value=None):
547547
"""Generate info string for Future."""
548548
return"GlobalCache.unwatch({})".format(key)
549549

@@ -580,7 +580,7 @@ def make_call(self):
580580
"""Call :method:`GlobalCache.compare_and_swap`."""
581581
return_global_cache().compare_and_swap(self.todo, expires=self.expires)
582582

583-
deffuture_info(self, key, value):
583+
deffuture_info(self, key, value=None):
584584
"""Generate info string for Future."""
585585
return"GlobalCache.compare_and_swap({}, {})".format(key, value)
586586

@@ -627,8 +627,7 @@ def global_lock_for_write(key):
627627
tasklets.Future: Eventual result will be a lock value to be used later with
628628
:func:`global_unlock`.
629629
"""
630-
lock="."+str(uuid.uuid4())
631-
lock=lock.encode("ascii")
630+
lock= ("."+str(uuid.uuid4())).encode("ascii")
632631
utils.logging_debug(log, "lock for write: {}", lock)
633632

634633
defnew_value(old_value):

‎packages/google-cloud-ndb/google/cloud/ndb/_datastore_api.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ def lookup(key, options):
168168
ifuse_global_cacheandnotkey_locked:
169169
ifentity_pbisnot_NOT_FOUND:
170170
expires=context._global_cache_timeout(key, options)
171-
serialized=entity_pb._pb.SerializeToString()
171+
serialized=entity_pb._pb.SerializeToString()# type: ignore[attr-defined]
172172
yield_cache.global_compare_and_swap(
173173
cache_key, serialized, expires=expires
174174
)

‎packages/google-cloud-ndb/google/cloud/ndb/_datastore_query.py‎

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,10 @@ def has_next_async(self):
342342
ifself._batchisNone:
343343
yieldself._next_batch() # First time
344344

345+
ifself._batchisNone:
346+
raiseTypeError("self._batch cannot be None")
347+
ifself._indexisNone:
348+
raiseTypeError("self._index cannot be None")
345349
ifself._index<len(self._batch):
346350
raisetasklets.Return(True)
347351

@@ -359,7 +363,9 @@ def probably_has_next(self):
359363
return (
360364
self._batchisNone# Haven't even started yet
361365
orself._has_next_batch# There's another batch to fetch
362-
orself._index<len(self._batch) # Not done with current batch
366+
or (
367+
self._indexisnotNoneandself._index<len(self._batch)
368+
) # Not done with current batch
363369
)
364370

365371
@tasklets.tasklet
@@ -421,6 +427,10 @@ def next(self):
421427
self._cursor_before=None
422428
raiseStopIteration
423429

430+
ifself._batchisNone:
431+
raiseTypeError("self._batch cannot be None")
432+
ifself._indexisNone:
433+
raiseTypeError("self._index cannot be None")
424434
# Won't block
425435
next_result=self._batch[self._index]
426436
self._index+=1
@@ -446,7 +456,7 @@ def _peek(self):
446456
batch=self._batch
447457
index=self._index
448458

449-
ifbatchandindex<len(batch):
459+
ifbatchandindexisnotNoneandindex<len(batch):
450460
returnbatch[index]
451461

452462
raiseKeyError(index)
@@ -554,6 +564,8 @@ def next(self):
554564
ifnotself.has_next():
555565
raiseStopIteration()
556566

567+
ifself._next_resultisNone:
568+
raiseTypeError("self._next_result cannot be None")
557569
# Won't block
558570
next_result=self._next_result
559571
self._next_result=None
@@ -718,6 +730,8 @@ def next(self):
718730
ifnotself.has_next():
719731
raiseStopIteration()
720732

733+
ifself._next_resultisNone:
734+
raiseTypeError("self._next_result cannot be None")
721735
# Won't block
722736
next_result=self._next_result
723737
self._next_result=None
@@ -949,7 +963,7 @@ def _query_to_protobuf(query):
949963
filter_pb=ancestor_filter_pb
950964

951965
elifisinstance(filter_pb, query_pb2.CompositeFilter):
952-
filter_pb.filters._pb.add(property_filter=ancestor_filter_pb._pb)
966+
filter_pb.filters._pb.add(property_filter=ancestor_filter_pb._pb)# type: ignore[attr-defined]
953967

954968
else:
955969
filter_pb=query_pb2.CompositeFilter(

‎packages/google-cloud-ndb/google/cloud/ndb/_eventloop.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,12 +116,15 @@ class EventLoop(object):
116116
"""
117117

118118
def__init__(self):
119-
self.current=collections.deque()
120-
self.idlers=collections.deque()
119+
self._init()
120+
121+
def_init(self):
122+
self.current: collections.deque=collections.deque()
123+
self.idlers: collections.deque=collections.deque()
121124
self.inactive=0
122125
self.queue= []
123126
self.rpcs= {}
124-
self.rpc_results=queue.Queue()
127+
self.rpc_results: queue.Queue=queue.Queue()
125128

126129
defclear(self):
127130
"""Remove all pending events without running any."""
@@ -139,7 +142,7 @@ def clear(self):
139142
utils.logging_debug(log, " queue = {}", queue)
140143
ifrpcs:
141144
utils.logging_debug(log, " rpcs = {}", rpcs)
142-
self.__init__()
145+
self._init()
143146
current.clear()
144147
idlers.clear()
145148
queue[:] = []

‎packages/google-cloud-ndb/google/cloud/ndb/_gql.py‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
importdatetime
22
importre
33
importtime
4+
fromtypingimportAny
45

56
fromgoogle.cloud.ndbimportcontextascontext_module
67
fromgoogle.cloud.ndbimportexceptions
@@ -408,7 +409,8 @@ def _AddProcessedParameterFilter(self, identifier, condition, operator, paramete
408409
ifidentifier.lower() =="ancestor":
409410
self._has_ancestor=True
410411
filter_rule= (self._ANCESTOR, "is")
411-
assertcondition.lower() =="is"
412+
ifcondition.lower() !="is":
413+
raiseValueError("condition must be 'is'")
412414

413415
ifoperator=="list"andcondition.lower() notin ["in", "not_in"]:
414416
self._Error("Only IN can process a list of values, given '%s'"%condition)
@@ -485,7 +487,7 @@ def _Literal(self):
485487
a string, integer, floating point value, boolean or None).
486488
"""
487489

488-
literal=None
490+
literal: Any=None
489491

490492
ifself._next_symbol<len(self._symbols):
491493
try:
@@ -770,27 +772,38 @@ def _raise_cast_error(message):
770772

771773

772774
def_time_function(values):
775+
t_tuple: tuple[int, ...]
773776
iflen(values) ==1:
774777
value=values[0]
775778
ifisinstance(value, str):
776779
try:
777-
time_tuple=time.strptime(value, "%H:%M:%S")
780+
parsed_time=time.strptime(value, "%H:%M:%S")
778781
exceptValueErroraserror:
779782
_raise_cast_error(
780783
"Error during time conversion, {}, {}".format(error, values)
781784
)
782-
time_tuple=time_tuple[3:]
783-
time_tuple=time_tuple[0:3]
785+
t_tuple= (
786+
parsed_time.tm_hour,
787+
parsed_time.tm_min,
788+
parsed_time.tm_sec,
789+
)
784790
elifisinstance(value, int):
785-
time_tuple= (value,)
791+
t_tuple= (value,)
786792
else:
787793
_raise_cast_error("Invalid argument for time(), {}".format(value))
788794
eliflen(values) <4:
789-
time_tuple=tuple(values)
795+
t_tuple=tuple(values)
790796
else:
791797
_raise_cast_error("Too many arguments for time(), {}".format(values))
792798
try:
793-
returndatetime.time(*time_tuple)
799+
iflen(t_tuple) ==1:
800+
returndatetime.time(t_tuple[0])
801+
eliflen(t_tuple) ==2:
802+
returndatetime.time(t_tuple[0], t_tuple[1])
803+
eliflen(t_tuple) ==3:
804+
returndatetime.time(t_tuple[0], t_tuple[1], t_tuple[2])
805+
else:
806+
_raise_cast_error("Invalid arguments for time()")
794807
exceptValueErroraserror:
795808
_raise_cast_error("Error during time conversion, {}, {}".format(error, values))
796809

‎packages/google-cloud-ndb/google/cloud/ndb/_legacy_entity_pb.py‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -389,11 +389,10 @@ class Property(ProtocolBuffer.ProtocolMessage):
389389
24: "EMPTY_LIST",
390390
}
391391

392+
@classmethod
392393
defMeaning_Name(cls, x):
393394
returncls._Meaning_NAMES.get(x, "")
394395

395-
Meaning_Name=classmethod(Meaning_Name)
396-
397396
has_meaning_=0
398397
meaning_=0
399398
has_meaning_uri_=0
@@ -526,7 +525,7 @@ class Path_Element(ProtocolBuffer.ProtocolMessage):
526525
deftype(self):
527526
# Force legacy byte-str to be a str.
528527
iftype(self.type_) isbytes:
529-
returnself.type_.decode()
528+
returnself.type_.decode()# type: ignore[attr-defined]
530529
returnself.type_
531530

532531
defset_type(self, x):

‎packages/google-cloud-ndb/google/cloud/ndb/_legacy_protocol_buffer.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ def MergePartialFromString(self, s):
3232
d=Decoder(a, 0, len(a))
3333
self.TryMerge(d)
3434

35+
defTryMerge(self, d):
36+
raiseNotImplementedError
37+
3538

3639
classDecoder:
3740
NUMERIC=0

‎packages/google-cloud-ndb/google/cloud/ndb/_options.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,16 @@
1919
importlogging
2020

2121
fromgoogle.cloud.ndbimportexceptions
22+
fromtypingimportAny
2223

2324
log=logging.getLogger(__name__)
2425

2526

2627
classOptions(object):
28+
max_memcache_items: Any
29+
force_writes: Any
30+
propagation: Any
31+
2732
__slots__= (
2833
# Supported
2934
"retries",

‎packages/google-cloud-ndb/google/cloud/ndb/_remote.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def __init__(self, future, info):
4141
self.future=future
4242
self.info=info
4343
self.start_time=time.time()
44-
self.elapsed_time=0
44+
self.elapsed_time=0.0
4545

4646
defrecord_time(future):
4747
self.elapsed_time=time.time() -self.start_time

0 commit comments

Comments
 (0)