Skip to content

Commit 815d266

Browse files
authored
Merge pull request #8 from ns-rse/ns-rse/numpy_complex_deprecation
feature: handle Numpy type deprecation & backwards compatibility
2 parents 664daf7 + e530351 commit 815d266

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

numpyencoder/numpyencoder.py

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,29 @@
1+
import warnings
2+
from packaging.version import parse as parse_version
13
import json
24
import numpy as np
35

46

7+
# Both np.float_ and np.complex_ were deprecated in Numpy 2.0.0
8+
if parse_version(np.__version__) < parse_version("2.0.0"):
9+
TYPES = {
10+
"float": (np.float_, np.float16, np.float32, np.float64),
11+
"complex": (np.complex_, np.complex64, np.complex128),
12+
}
13+
warnings.warn(
14+
f"You are using an old version of Numpy ({np.__version__}), "
15+
"support for 'np.float_' and 'np.complex_' were deprecated "
16+
"in Numpy 2.0.0. If you use these datatypes in your code "
17+
"please consider updating them.",
18+
category=DeprecationWarning,
19+
)
20+
else:
21+
TYPES = {
22+
"float": (np.float16, np.float32, np.float64),
23+
"complex": (np.complex64, np.complex128),
24+
}
25+
26+
527
class NumpyEncoder(json.JSONEncoder):
628
"""Custom encoder for numpy data types"""
729

@@ -22,13 +44,12 @@ def default(self, obj):
2244
np.uint64,
2345
),
2446
):
25-
2647
return int(obj)
2748

28-
elif isinstance(obj, (np.float16, np.float32, np.float64)):
49+
elif isinstance(obj, TYPES["float"]):
2950
return float(obj)
3051

31-
elif isinstance(obj, (np.complex_, np.complex64, np.complex128)):
52+
elif isinstance(obj, TYPES["complex"]):
3253
return {"real": obj.real, "imag": obj.imag}
3354

3455
elif isinstance(obj, (np.ndarray,)):

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
setup(
77
name="numpyencoder",
8-
version="0.3.1",
8+
version="0.3.2",
99
author="Hunter M. Allen",
1010
author_email="allenhm@gmail.com",
1111
license="MIT",

0 commit comments

Comments
 (0)