Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions numpyencoder/numpyencoder.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,29 @@
import warnings
from packaging.version import parse as parse_version
import json
import numpy as np


# Both np.float_ and np.complex_ were deprecated in Numpy 2.0.0
if parse_version(np.__version__) < parse_version("2.0.0"):
TYPES = {
"float": (np.float_, np.float16, np.float32, np.float64),
"complex": (np.complex_, np.complex64, np.complex128),
}
warnings.warn(
f"You are using an old version of Numpy ({np.__version__}), "
"support for 'np.float_' and 'np.complex_' were deprecated "
"in Numpy 2.0.0. If you use these datatypes in your code "
"please consider updating them.",
category=DeprecationWarning,
)
else:
TYPES = {
"float": (np.float16, np.float32, np.float64),
"complex": (np.complex64, np.complex128),
}


class NumpyEncoder(json.JSONEncoder):
"""Custom encoder for numpy data types"""

Expand All @@ -22,13 +44,12 @@ def default(self, obj):
np.uint64,
),
):

return int(obj)

elif isinstance(obj, (np.float16, np.float32, np.float64)):
elif isinstance(obj, TYPES["float"]):
return float(obj)

elif isinstance(obj, (np.complex_, np.complex64, np.complex128)):
elif isinstance(obj, TYPES["complex"]):
return {"real": obj.real, "imag": obj.imag}

elif isinstance(obj, (np.ndarray,)):
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name="numpyencoder",
version="0.3.1",
version="0.3.2",
author="Hunter M. Allen",
author_email="allenhm@gmail.com",
license="MIT",
Expand Down