Skip to content

Commit

Permalink
Throw TypeError around any call in `if hasattr(obj, '__iter__') a…
Browse files Browse the repository at this point in the history
…nd 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
  • Loading branch information
vtomole committed Aug 5, 2021
1 parent 120eb87 commit 2466bc3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
9 changes: 8 additions & 1 deletion cirq-core/cirq/protocols/json_serialization.py
Expand Up @@ -442,8 +442,15 @@ def has_serializable_by_keys(obj: Any) -> bool:
# Handle primitive container types.
if isinstance(obj, Dict):
return any(has_serializable_by_keys(elem) for pair in obj.items() for elem in pair)

if hasattr(obj, '__iter__') and not isinstance(obj, str):
return any(has_serializable_by_keys(elem) for elem in obj)
# Return False on TypeError because some numpy values
# (like np.array(1)) have iterable methods
# yet return a TypeError when there is an attempt to iterate over them
try:
return any(has_serializable_by_keys(elem) for elem in obj)
except TypeError:
return False
return False


Expand Down
9 changes: 9 additions & 0 deletions cirq-core/cirq/protocols/json_serialization_test.py
Expand Up @@ -796,3 +796,12 @@ def custom_resolver(name):
return QuantumVolumeParams

assert_json_roundtrip_works(qvp, resolvers=[custom_resolver] + cirq.DEFAULT_RESOLVERS)


def test_numpy_values():
assert (
cirq.to_json({'value': np.array(1)})
== """{
"value": 1
}"""
)

0 comments on commit 2466bc3

Please sign in to comment.