Import stdlib ABCs from 'collections.abc' rather than 'collections'. (#6451)
On Python 2.7, fall back to 'collections'.
Closes #6450.
diff --git a/google/api_core/protobuf_helpers.py b/google/api_core/protobuf_helpers.py
index ab6d5a2..78ab101 100644
--- a/google/api_core/protobuf_helpers.py
+++ b/google/api_core/protobuf_helpers.py
@@ -15,6 +15,10 @@
"""Helpers for :mod:`protobuf`."""
import collections
+try:
+ from collections import abc as collections_abc
+except ImportError: # Python 2.7
+ import collections as collections_abc
import copy
import inspect
@@ -161,7 +165,7 @@
# If we get something else, complain.
if isinstance(msg_or_dict, message.Message):
answer = getattr(msg_or_dict, key, default)
- elif isinstance(msg_or_dict, collections.Mapping):
+ elif isinstance(msg_or_dict, collections_abc.Mapping):
answer = msg_or_dict.get(key, default)
else:
raise TypeError(
@@ -184,7 +188,7 @@
"""Set helper for protobuf Messages."""
# Attempt to set the value on the types of objects we know how to deal
# with.
- if isinstance(value, (collections.MutableSequence, tuple)):
+ if isinstance(value, (collections_abc.MutableSequence, tuple)):
# Clear the existing repeated protobuf message of any elements
# currently inside it.
while getattr(msg, key):
@@ -192,13 +196,13 @@
# Write our new elements to the repeated field.
for item in value:
- if isinstance(item, collections.Mapping):
+ if isinstance(item, collections_abc.Mapping):
getattr(msg, key).add(**item)
else:
# protobuf's RepeatedCompositeContainer doesn't support
# append.
getattr(msg, key).extend([item])
- elif isinstance(value, collections.Mapping):
+ elif isinstance(value, collections_abc.Mapping):
# Assign the dictionary values to the protobuf message.
for item_key, item_value in value.items():
set(getattr(msg, key), item_key, item_value)
@@ -222,7 +226,7 @@
"""
# Sanity check: Is our target object valid?
if (not isinstance(msg_or_dict,
- (collections.MutableMapping, message.Message))):
+ (collections_abc.MutableMapping, message.Message))):
raise TypeError(
'set() expected a dict or protobuf message, got {!r}.'.format(
type(msg_or_dict)))
@@ -233,12 +237,12 @@
# If a subkey exists, then get that object and call this method
# recursively against it using the subkey.
if subkey is not None:
- if isinstance(msg_or_dict, collections.MutableMapping):
+ if isinstance(msg_or_dict, collections_abc.MutableMapping):
msg_or_dict.setdefault(basekey, {})
set(get(msg_or_dict, basekey), subkey, value)
return
- if isinstance(msg_or_dict, collections.MutableMapping):
+ if isinstance(msg_or_dict, collections_abc.MutableMapping):
msg_or_dict[key] = value
else:
_set_field_on_message(msg_or_dict, key, value)