google-cloud-ndb 2.4.1__tar.gz → 2.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. {google_cloud_ndb-2.4.1/google_cloud_ndb.egg-info → google_cloud_ndb-2.5.0}/PKG-INFO +6 -7
  2. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/README.md +2 -2
  3. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/__init__.py +1 -1
  4. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_cache.py +11 -12
  5. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_datastore_api.py +1 -1
  6. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_datastore_query.py +17 -3
  7. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_eventloop.py +7 -4
  8. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_gql.py +21 -8
  9. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_legacy_entity_pb.py +2 -3
  10. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_legacy_protocol_buffer.py +3 -0
  11. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_options.py +5 -0
  12. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_remote.py +1 -1
  13. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_retry.py +3 -3
  14. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_transaction.py +2 -2
  15. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/context.py +15 -5
  16. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/global_cache.py +5 -4
  17. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/key.py +4 -3
  18. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/model.py +146 -78
  19. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/polymodel.py +2 -2
  20. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/query.py +24 -7
  21. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/tasklets.py +1 -0
  22. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/version.py +1 -1
  23. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0/google_cloud_ndb.egg-info}/PKG-INFO +6 -7
  24. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google_cloud_ndb.egg-info/requires.txt +2 -2
  25. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/setup.py +3 -4
  26. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/AUTHORS +0 -0
  27. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/LICENSE +0 -0
  28. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_batch.py +0 -0
  29. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/_datastore_types.py +0 -0
  30. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/blobstore.py +0 -0
  31. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/client.py +0 -0
  32. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/django_middleware.py +0 -0
  33. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/exceptions.py +0 -0
  34. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/metadata.py +0 -0
  35. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/msgprop.py +0 -0
  36. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/stats.py +0 -0
  37. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google/cloud/ndb/utils.py +0 -0
  38. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google_cloud_ndb.egg-info/SOURCES.txt +0 -0
  39. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google_cloud_ndb.egg-info/dependency_links.txt +0 -0
  40. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google_cloud_ndb.egg-info/not-zip-safe +0 -0
  41. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/google_cloud_ndb.egg-info/top_level.txt +0 -0
  42. {google_cloud_ndb-2.4.1 → google_cloud_ndb-2.5.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: google-cloud-ndb
3
- Version: 2.4.1
3
+ Version: 2.5.0
4
4
  Summary: NDB library for Google Cloud Datastore
5
5
  Home-page: https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-ndb
6
6
  Author: Google LLC
@@ -14,7 +14,6 @@ Classifier: Intended Audience :: Developers
14
14
  Classifier: License :: OSI Approved :: Apache Software License
15
15
  Classifier: Programming Language :: Python
16
16
  Classifier: Programming Language :: Python :: 3
17
- Classifier: Programming Language :: Python :: 3.9
18
17
  Classifier: Programming Language :: Python :: 3.10
19
18
  Classifier: Programming Language :: Python :: 3.11
20
19
  Classifier: Programming Language :: Python :: 3.12
@@ -22,7 +21,7 @@ Classifier: Programming Language :: Python :: 3.13
22
21
  Classifier: Programming Language :: Python :: 3.14
23
22
  Classifier: Operating System :: OS Independent
24
23
  Classifier: Topic :: Internet
25
- Requires-Python: >=3.9
24
+ Requires-Python: >=3.10
26
25
  Description-Content-Type: text/markdown
27
26
  License-File: LICENSE
28
27
  License-File: AUTHORS
@@ -30,8 +29,8 @@ Requires-Dist: google-api-core[grpc]<3.0.0,>=2.11.0
30
29
  Requires-Dist: google-cloud-datastore!=2.20.2,<3.0.0,>=2.16.0
31
30
  Requires-Dist: protobuf<8.0.0,>=4.25.8
32
31
  Requires-Dist: pymemcache<5.0.0,>=2.1.0
33
- Requires-Dist: pytz>=2018.3
34
- Requires-Dist: redis<7.0.0,>=3.0.0
32
+ Requires-Dist: pytz>=2022.1
33
+ Requires-Dist: redis<8.0.0,>=3.0.0
35
34
  Dynamic: author
36
35
  Dynamic: author-email
37
36
  Dynamic: classifier
@@ -78,14 +77,14 @@ GA
78
77
 
79
78
  Our client libraries are compatible with all current [active][3] and [maintenance][4] versions of Python.
80
79
 
81
- Python >= 3.9
80
+ Python >= 3.10
82
81
 
83
82
  [3]: https://devguide.python.org/devcycle/#in-development-main-branch
84
83
  [4]: https://devguide.python.org/devcycle/#maintenance-branches
85
84
 
86
85
  ### Unsupported Python Versions
87
86
 
88
- Python <= 3.8
87
+ Python <= 3.9
89
88
 
90
89
  If you are using an [end-of-life][5]
91
90
  version of Python, we recommend that you update as soon as possible to an actively supported version.
@@ -30,14 +30,14 @@ GA
30
30
 
31
31
  Our client libraries are compatible with all current [active][3] and [maintenance][4] versions of Python.
32
32
 
33
- Python >= 3.9
33
+ Python >= 3.10
34
34
 
35
35
  [3]: https://devguide.python.org/devcycle/#in-development-main-branch
36
36
  [4]: https://devguide.python.org/devcycle/#maintenance-branches
37
37
 
38
38
  ### Unsupported Python Versions
39
39
 
40
- Python <= 3.8
40
+ Python <= 3.9
41
41
 
42
42
  If you are using an [end-of-life][5]
43
43
  version of Python, we recommend that you update as soon as possible to an actively supported version.
@@ -23,7 +23,7 @@ version of the ``db`` API (hence ``ndb``).
23
23
 
24
24
  from google.cloud.ndb import version
25
25
 
26
- __version__ = version.__version__
26
+ __version__: str = version.__version__
27
27
 
28
28
  from google.cloud.ndb.client import Client
29
29
  from google.cloud.ndb.context import AutoBatcher
@@ -117,18 +117,18 @@ class _GlobalCacheBatch(object):
117
117
  """
118
118
  exception = cache_call.exception()
119
119
  if exception:
120
- for future in self.futures:
120
+ for future in self.futures: # type: ignore[attr-defined]
121
121
  future.set_exception(exception)
122
122
 
123
123
  else:
124
- for future in self.futures:
124
+ for future in self.futures: # type: ignore[attr-defined]
125
125
  future.set_result(None)
126
126
 
127
127
  def make_call(self):
128
128
  """Make the actual call to the global cache. To be overridden."""
129
129
  raise NotImplementedError
130
130
 
131
- def future_info(self, key):
131
+ def future_info(self, key, value=None):
132
132
  """Generate info string for Future. To be overridden."""
133
133
  raise NotImplementedError
134
134
 
@@ -279,7 +279,7 @@ class _GlobalCacheGetBatch(_GlobalCacheBatch):
279
279
  """Call :method:`GlobalCache.get`."""
280
280
  return _global_cache().get(self.keys)
281
281
 
282
- def future_info(self, key):
282
+ def future_info(self, key, value=None):
283
283
  """Generate info string for Future."""
284
284
  return "GlobalCache.get({})".format(key)
285
285
 
@@ -373,7 +373,7 @@ class _GlobalCacheSetBatch(_GlobalCacheBatch):
373
373
  """Call :method:`GlobalCache.set`."""
374
374
  return _global_cache().set(self.todo, expires=self.expires)
375
375
 
376
- def future_info(self, key, value):
376
+ def future_info(self, key, value=None):
377
377
  """Generate info string for Future."""
378
378
  return "GlobalCache.set({}, {})".format(key, value)
379
379
 
@@ -436,7 +436,7 @@ class _GlobalCacheSetIfNotExistsBatch(_GlobalCacheSetBatch):
436
436
  """Call :method:`GlobalCache.set`."""
437
437
  return _global_cache().set_if_not_exists(self.todo, expires=self.expires)
438
438
 
439
- def future_info(self, key, value):
439
+ def future_info(self, key, value=None):
440
440
  """Generate info string for Future."""
441
441
  return "GlobalCache.set_if_not_exists({}, {})".format(key, value)
442
442
 
@@ -482,7 +482,7 @@ class _GlobalCacheDeleteBatch(_GlobalCacheBatch):
482
482
  """Call :method:`GlobalCache.delete`."""
483
483
  return _global_cache().delete(self.keys)
484
484
 
485
- def future_info(self, key):
485
+ def future_info(self, key, value=None):
486
486
  """Generate info string for Future."""
487
487
  return "GlobalCache.delete({})".format(key)
488
488
 
@@ -513,7 +513,7 @@ class _GlobalCacheWatchBatch(_GlobalCacheSetBatch):
513
513
  """Call :method:`GlobalCache.watch`."""
514
514
  return _global_cache().watch(self.todo)
515
515
 
516
- def future_info(self, key, value):
516
+ def future_info(self, key, value=None):
517
517
  """Generate info string for Future."""
518
518
  return "GlobalCache.watch({}, {})".format(key, value)
519
519
 
@@ -543,7 +543,7 @@ class _GlobalCacheUnwatchBatch(_GlobalCacheDeleteBatch):
543
543
  """Call :method:`GlobalCache.unwatch`."""
544
544
  return _global_cache().unwatch(self.keys)
545
545
 
546
- def future_info(self, key):
546
+ def future_info(self, key, value=None):
547
547
  """Generate info string for Future."""
548
548
  return "GlobalCache.unwatch({})".format(key)
549
549
 
@@ -580,7 +580,7 @@ class _GlobalCacheCompareAndSwapBatch(_GlobalCacheSetBatch):
580
580
  """Call :method:`GlobalCache.compare_and_swap`."""
581
581
  return _global_cache().compare_and_swap(self.todo, expires=self.expires)
582
582
 
583
- def future_info(self, key, value):
583
+ def future_info(self, key, value=None):
584
584
  """Generate info string for Future."""
585
585
  return "GlobalCache.compare_and_swap({}, {})".format(key, value)
586
586
 
@@ -627,8 +627,7 @@ def global_lock_for_write(key):
627
627
  tasklets.Future: Eventual result will be a lock value to be used later with
628
628
  :func:`global_unlock`.
629
629
  """
630
- lock = "." + str(uuid.uuid4())
631
- lock = lock.encode("ascii")
630
+ lock = ("." + str(uuid.uuid4())).encode("ascii")
632
631
  utils.logging_debug(log, "lock for write: {}", lock)
633
632
 
634
633
  def new_value(old_value):
@@ -168,7 +168,7 @@ def lookup(key, options):
168
168
  if use_global_cache and not key_locked:
169
169
  if entity_pb is not _NOT_FOUND:
170
170
  expires = context._global_cache_timeout(key, options)
171
- serialized = entity_pb._pb.SerializeToString()
171
+ serialized = entity_pb._pb.SerializeToString() # type: ignore[attr-defined]
172
172
  yield _cache.global_compare_and_swap(
173
173
  cache_key, serialized, expires=expires
174
174
  )
@@ -342,6 +342,10 @@ class _QueryIteratorImpl(QueryIterator):
342
342
  if self._batch is None:
343
343
  yield self._next_batch() # First time
344
344
 
345
+ if self._batch is None:
346
+ raise TypeError("self._batch cannot be None")
347
+ if self._index is None:
348
+ raise TypeError("self._index cannot be None")
345
349
  if self._index < len(self._batch):
346
350
  raise tasklets.Return(True)
347
351
 
@@ -359,7 +363,9 @@ class _QueryIteratorImpl(QueryIterator):
359
363
  return (
360
364
  self._batch is None # Haven't even started yet
361
365
  or self._has_next_batch # There's another batch to fetch
362
- or self._index < len(self._batch) # Not done with current batch
366
+ or (
367
+ self._index is not None and self._index < len(self._batch)
368
+ ) # Not done with current batch
363
369
  )
364
370
 
365
371
  @tasklets.tasklet
@@ -421,6 +427,10 @@ class _QueryIteratorImpl(QueryIterator):
421
427
  self._cursor_before = None
422
428
  raise StopIteration
423
429
 
430
+ if self._batch is None:
431
+ raise TypeError("self._batch cannot be None")
432
+ if self._index is None:
433
+ raise TypeError("self._index cannot be None")
424
434
  # Won't block
425
435
  next_result = self._batch[self._index]
426
436
  self._index += 1
@@ -446,7 +456,7 @@ class _QueryIteratorImpl(QueryIterator):
446
456
  batch = self._batch
447
457
  index = self._index
448
458
 
449
- if batch and index < len(batch):
459
+ if batch and index is not None and index < len(batch):
450
460
  return batch[index]
451
461
 
452
462
  raise KeyError(index)
@@ -554,6 +564,8 @@ class _PostFilterQueryIteratorImpl(QueryIterator):
554
564
  if not self.has_next():
555
565
  raise StopIteration()
556
566
 
567
+ if self._next_result is None:
568
+ raise TypeError("self._next_result cannot be None")
557
569
  # Won't block
558
570
  next_result = self._next_result
559
571
  self._next_result = None
@@ -718,6 +730,8 @@ class _MultiQueryIteratorImpl(QueryIterator):
718
730
  if not self.has_next():
719
731
  raise StopIteration()
720
732
 
733
+ if self._next_result is None:
734
+ raise TypeError("self._next_result cannot be None")
721
735
  # Won't block
722
736
  next_result = self._next_result
723
737
  self._next_result = None
@@ -949,7 +963,7 @@ def _query_to_protobuf(query):
949
963
  filter_pb = ancestor_filter_pb
950
964
 
951
965
  elif isinstance(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]
953
967
 
954
968
  else:
955
969
  filter_pb = query_pb2.CompositeFilter(
@@ -116,12 +116,15 @@ class EventLoop(object):
116
116
  """
117
117
 
118
118
  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()
121
124
  self.inactive = 0
122
125
  self.queue = []
123
126
  self.rpcs = {}
124
- self.rpc_results = queue.Queue()
127
+ self.rpc_results: queue.Queue = queue.Queue()
125
128
 
126
129
  def clear(self):
127
130
  """Remove all pending events without running any."""
@@ -139,7 +142,7 @@ class EventLoop(object):
139
142
  utils.logging_debug(log, " queue = {}", queue)
140
143
  if rpcs:
141
144
  utils.logging_debug(log, " rpcs = {}", rpcs)
142
- self.__init__()
145
+ self._init()
143
146
  current.clear()
144
147
  idlers.clear()
145
148
  queue[:] = []
@@ -1,6 +1,7 @@
1
1
  import datetime
2
2
  import re
3
3
  import time
4
+ from typing import Any
4
5
 
5
6
  from google.cloud.ndb import context as context_module
6
7
  from google.cloud.ndb import exceptions
@@ -408,7 +409,8 @@ class GQL(object):
408
409
  if identifier.lower() == "ancestor":
409
410
  self._has_ancestor = True
410
411
  filter_rule = (self._ANCESTOR, "is")
411
- assert condition.lower() == "is"
412
+ if condition.lower() != "is":
413
+ raise ValueError("condition must be 'is'")
412
414
 
413
415
  if operator == "list" and condition.lower() not in ["in", "not_in"]:
414
416
  self._Error("Only IN can process a list of values, given '%s'" % condition)
@@ -485,7 +487,7 @@ class GQL(object):
485
487
  a string, integer, floating point value, boolean or None).
486
488
  """
487
489
 
488
- literal = None
490
+ literal: Any = None
489
491
 
490
492
  if self._next_symbol < len(self._symbols):
491
493
  try:
@@ -770,27 +772,38 @@ def _raise_cast_error(message):
770
772
 
771
773
 
772
774
  def _time_function(values):
775
+ t_tuple: tuple[int, ...]
773
776
  if len(values) == 1:
774
777
  value = values[0]
775
778
  if isinstance(value, str):
776
779
  try:
777
- time_tuple = time.strptime(value, "%H:%M:%S")
780
+ parsed_time = time.strptime(value, "%H:%M:%S")
778
781
  except ValueError as error:
779
782
  _raise_cast_error(
780
783
  "Error during time conversion, {}, {}".format(error, values)
781
784
  )
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
+ )
784
790
  elif isinstance(value, int):
785
- time_tuple = (value,)
791
+ t_tuple = (value,)
786
792
  else:
787
793
  _raise_cast_error("Invalid argument for time(), {}".format(value))
788
794
  elif len(values) < 4:
789
- time_tuple = tuple(values)
795
+ t_tuple = tuple(values)
790
796
  else:
791
797
  _raise_cast_error("Too many arguments for time(), {}".format(values))
792
798
  try:
793
- return datetime.time(*time_tuple)
799
+ if len(t_tuple) == 1:
800
+ return datetime.time(t_tuple[0])
801
+ elif len(t_tuple) == 2:
802
+ return datetime.time(t_tuple[0], t_tuple[1])
803
+ elif len(t_tuple) == 3:
804
+ return datetime.time(t_tuple[0], t_tuple[1], t_tuple[2])
805
+ else:
806
+ _raise_cast_error("Invalid arguments for time()")
794
807
  except ValueError as error:
795
808
  _raise_cast_error("Error during time conversion, {}, {}".format(error, values))
796
809
 
@@ -389,11 +389,10 @@ class Property(ProtocolBuffer.ProtocolMessage):
389
389
  24: "EMPTY_LIST",
390
390
  }
391
391
 
392
+ @classmethod
392
393
  def Meaning_Name(cls, x):
393
394
  return cls._Meaning_NAMES.get(x, "")
394
395
 
395
- Meaning_Name = classmethod(Meaning_Name)
396
-
397
396
  has_meaning_ = 0
398
397
  meaning_ = 0
399
398
  has_meaning_uri_ = 0
@@ -526,7 +525,7 @@ class Path_Element(ProtocolBuffer.ProtocolMessage):
526
525
  def type(self):
527
526
  # Force legacy byte-str to be a str.
528
527
  if type(self.type_) is bytes:
529
- return self.type_.decode()
528
+ return self.type_.decode() # type: ignore[attr-defined]
530
529
  return self.type_
531
530
 
532
531
  def set_type(self, x):
@@ -32,6 +32,9 @@ class ProtocolMessage:
32
32
  d = Decoder(a, 0, len(a))
33
33
  self.TryMerge(d)
34
34
 
35
+ def TryMerge(self, d):
36
+ raise NotImplementedError
37
+
35
38
 
36
39
  class Decoder:
37
40
  NUMERIC = 0
@@ -19,11 +19,16 @@ import itertools
19
19
  import logging
20
20
 
21
21
  from google.cloud.ndb import exceptions
22
+ from typing import Any
22
23
 
23
24
  log = logging.getLogger(__name__)
24
25
 
25
26
 
26
27
  class Options(object):
28
+ max_memcache_items: Any
29
+ force_writes: Any
30
+ propagation: Any
31
+
27
32
  __slots__ = (
28
33
  # Supported
29
34
  "retries",
@@ -41,7 +41,7 @@ class RemoteCall(object):
41
41
  self.future = future
42
42
  self.info = info
43
43
  self.start_time = time.time()
44
- self.elapsed_time = 0
44
+ self.elapsed_time = 0.0
45
45
 
46
46
  def record_time(future):
47
47
  self.elapsed_time = time.time() - self.start_time
@@ -33,7 +33,7 @@ def wraps_safely(obj, attr_names=functools.WRAPPER_ASSIGNMENTS):
33
33
  are not copied to the wrappers and thus cause attribute errors. This
34
34
  wrapper prevents that problem."""
35
35
  return functools.wraps(
36
- obj, assigned=(name for name in attr_names if hasattr(obj, name))
36
+ obj, assigned=tuple(name for name in attr_names if hasattr(obj, name))
37
37
  )
38
38
 
39
39
 
@@ -84,7 +84,7 @@ def retry_async(callback, retries=_DEFAULT_RETRIES):
84
84
  error = e
85
85
  except BaseException as e:
86
86
  # `e` is removed from locals at end of block
87
- error = e # See: https://goo.gl/5J8BMK
87
+ error = e # type: ignore[assignment] # See: https://goo.gl/5J8BMK
88
88
 
89
89
  if not is_transient_error(error):
90
90
  # If we are in an inner retry block, use special nested
@@ -107,7 +107,7 @@ def retry_async(callback, retries=_DEFAULT_RETRIES):
107
107
 
108
108
  # Unknown errors really want to show up as None, so manually set the error.
109
109
  if isinstance(error, core_exceptions.Unknown):
110
- error = "google.api_core.exceptions.Unknown"
110
+ error = "google.api_core.exceptions.Unknown" # type: ignore[assignment]
111
111
 
112
112
  raise core_exceptions.RetryError(
113
113
  "Maximum number of {} retries exceeded while calling {}".format(
@@ -257,8 +257,8 @@ def _transaction_async(context, callback, read_only=False):
257
257
  transaction_id = yield _datastore_api.begin_transaction(read_only, retries=0)
258
258
  utils.logging_debug(log, "Transaction Id: {}", transaction_id)
259
259
 
260
- on_commit_callbacks = []
261
- transaction_complete_callbacks = []
260
+ on_commit_callbacks: list = []
261
+ transaction_complete_callbacks: list = []
262
262
  tx_context = context.new(
263
263
  transaction=transaction_id,
264
264
  on_commit_callbacks=on_commit_callbacks,
@@ -22,6 +22,7 @@ import itertools
22
22
  import os
23
23
  import threading
24
24
  import uuid
25
+ from typing import Any, cast
25
26
 
26
27
  from google.cloud.ndb import _eventloop
27
28
  from google.cloud.ndb import exceptions
@@ -254,6 +255,11 @@ class _Context(_ContextTuple):
254
255
  client (client.Client): The NDB client for this context.
255
256
  """
256
257
 
258
+ cache_policy: Any
259
+ global_cache_policy: Any
260
+ global_cache_timeout_policy: Any
261
+ datastore_policy: Any
262
+
257
263
  def __new__(
258
264
  cls,
259
265
  client,
@@ -313,11 +319,15 @@ class _Context(_ContextTuple):
313
319
  legacy_data=legacy_data,
314
320
  )
315
321
 
316
- context.set_cache_policy(cache_policy)
317
- context.set_global_cache_policy(global_cache_policy)
318
- context.set_global_cache_timeout_policy(global_cache_timeout_policy)
319
- context.set_datastore_policy(datastore_policy)
320
- context.set_retry_state(retry)
322
+ # 'context' is dynamically composed at runtime and may include methods
323
+ # from multiple sources that Mypy cannot statically resolve here.
324
+ # We cast to `Any` to access the extended policy interface.
325
+ ctx = cast(Any, context)
326
+ ctx.set_cache_policy(cache_policy)
327
+ ctx.set_global_cache_policy(global_cache_policy)
328
+ ctx.set_global_cache_timeout_policy(global_cache_timeout_policy)
329
+ ctx.set_datastore_policy(datastore_policy)
330
+ ctx.set_retry_state(retry)
321
331
 
322
332
  return context
323
333
 
@@ -26,6 +26,7 @@ import warnings
26
26
 
27
27
  import pymemcache
28
28
  import redis as redis_module
29
+ from typing import Any
29
30
 
30
31
  # Python 2.7 doesn't have ConnectionError. In Python 3, ConnectionError is subclass of
31
32
  # OSError, which Python 2.7 does have.
@@ -71,7 +72,7 @@ class GlobalCache(object):
71
72
 
72
73
  __metaclass__ = abc.ABCMeta
73
74
 
74
- transient_errors = ()
75
+ transient_errors: tuple[type, ...] = ()
75
76
  """Exceptions that should be treated as transient errors in non-strict modes.
76
77
 
77
78
  Instances of these exceptions, if raised, will be logged as warnings but will not
@@ -202,7 +203,7 @@ class _InProcessGlobalCache(GlobalCache):
202
203
  reference implementation. Thread safety is potentially a little sketchy.
203
204
  """
204
205
 
205
- cache = {}
206
+ cache: dict[Any, Any] = {}
206
207
  """Dict: The cache.
207
208
 
208
209
  Relies on atomicity of ``__setitem__`` for thread safety. See:
@@ -521,9 +522,9 @@ class MemcacheCache(GlobalCache):
521
522
 
522
523
  @staticmethod
523
524
  def _key(key):
524
- encoded = base64.b64encode(key)
525
+ encoded = base64.b64encode(key).decode("ascii")
525
526
  if len(encoded) > 250:
526
- encoded = hashlib.sha1(encoded).hexdigest()
527
+ encoded = hashlib.sha1(encoded.encode("ascii")).hexdigest()
527
528
  return encoded
528
529
 
529
530
  @classmethod
@@ -88,6 +88,7 @@ namespace. To explicitly select the empty namespace pass ``namespace=""``.
88
88
  """
89
89
 
90
90
 
91
+ import typing
91
92
  import base64
92
93
  import functools
93
94
 
@@ -1315,7 +1316,7 @@ def _parse_from_ref(
1315
1316
  urlsafe=None,
1316
1317
  app=None,
1317
1318
  namespace=None,
1318
- database: str = None,
1319
+ database: typing.Optional[str] = None,
1319
1320
  **kwargs
1320
1321
  ):
1321
1322
  """Construct a key from a Reference.
@@ -1523,7 +1524,7 @@ def _clean_flat_path(flat):
1523
1524
  # Make sure the ``kind`` is either a string or a Model.
1524
1525
  kind = flat[i]
1525
1526
  if isinstance(kind, type):
1526
- kind = kind._get_kind()
1527
+ kind = kind._get_kind() # type: ignore[attr-defined]
1527
1528
  flat[i] = kind
1528
1529
  if not isinstance(kind, str):
1529
1530
  raise TypeError(
@@ -1607,7 +1608,7 @@ def _to_legacy_path(dict_path):
1607
1608
  element_kwargs["id"] = _verify_path_value(part["id"], False)
1608
1609
  elif "name" in part:
1609
1610
  element_kwargs["name"] = _verify_path_value(part["name"], True)
1610
- element = _app_engine_key_pb2.Path.Element(**element_kwargs)
1611
+ element = _app_engine_key_pb2.Path.Element(**element_kwargs) # type: ignore[attr-defined]
1611
1612
  elements.append(element)
1612
1613
 
1613
1614
  return _app_engine_key_pb2.Path(element=elements)