Skip to content

Commit 2466bc3

Browse files
authored
Throw TypeError around any call in if hasattr(obj, '__iter__') and not isinstance(obj, str): to deal with a numpy special case (#4382)
This `TypeError` is thrown from the `numpy` source: https://github.com/numpy/numpy/blob/ffcf508951f646c2ae02c2a0583b884f7a9163e8/numpy/core/src/multiarray/arrayobject.c#L1700-L1702 Fixes: #4030
1 parent 120eb87 commit 2466bc3

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

cirq-core/cirq/protocols/json_serialization.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -442,8 +442,15 @@ def has_serializable_by_keys(obj: Any) -> bool:
442442
# Handle primitive container types.
443443
if isinstance(obj, Dict):
444444
return any(has_serializable_by_keys(elem) for pair in obj.items() for elem in pair)
445+
445446
if hasattr(obj, '__iter__') and not isinstance(obj, str):
446-
return any(has_serializable_by_keys(elem) for elem in obj)
447+
# Return False on TypeError because some numpy values
448+
# (like np.array(1)) have iterable methods
449+
# yet return a TypeError when there is an attempt to iterate over them
450+
try:
451+
return any(has_serializable_by_keys(elem) for elem in obj)
452+
except TypeError:
453+
return False
447454
return False
448455

449456

cirq-core/cirq/protocols/json_serialization_test.py

+9
Original file line numberDiff line numberDiff line change
@@ -796,3 +796,12 @@ def custom_resolver(name):
796796
return QuantumVolumeParams
797797

798798
assert_json_roundtrip_works(qvp, resolvers=[custom_resolver] + cirq.DEFAULT_RESOLVERS)
799+
800+
801+
def test_numpy_values():
802+
assert (
803+
cirq.to_json({'value': np.array(1)})
804+
== """{
805+
"value": 1
806+
}"""
807+
)

0 commit comments

Comments
 (0)