Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow (de)serializing CalendarRange and DateRange Parameters #625

Merged
merged 7 commits into from
May 17, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
45 changes: 45 additions & 0 deletions param/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2127,6 +2127,37 @@ def _validate_value(self, val, allow_None):
"is before start datetime %s." %
(self.name, val[1], val[0]))

@classmethod
def serialize(cls, value):
if value is None:
return 'null'
# List as JSON has no tuple representation
serialized = []
for v in value:
if not isinstance(v, (dt.datetime, dt.date)): # i.e np.datetime64
v = v.astype(dt.datetime)
# Separate date and datetime to deserialize to the right type.
if type(v) == dt.date:
v = v.strftime("%Y-%m-%d")
else:
v = v.strftime("%Y-%m-%dT%H:%M:%S.%f")
serialized.append(v)
return serialized

def deserialize(cls, value):
if value == 'null':
return None
deserialized = []
for v in value:
# Date
if len(v) == 10:
v = dt.datetime.strptime(v, "%Y-%m-%d").date()
# Datetime
else:
v = dt.datetime.strptime(v, "%Y-%m-%dT%H:%M:%S.%f")
deserialized.append(v)
# As JSON has no tuple representation
return tuple(deserialized)


class CalendarDateRange(Range):
Expand All @@ -2148,6 +2179,20 @@ def _validate_value(self, val, allow_None):
"%s is before start date %s." %
(self.name, val[1], val[0]))

@classmethod
def serialize(cls, value):
if value is None:
return 'null'
# As JSON has no tuple representation
return [v.strftime("%Y-%m-%d") for v in value]

@classmethod
def deserialize(cls, value):
if value == 'null':
return None
# As JSON has no tuple representation
return tuple([dt.datetime.strptime(v, "%Y-%m-%d").date() for v in value])


class Event(Boolean):
"""
Expand Down
77 changes: 75 additions & 2 deletions tests/API1/testjsonserialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,27 @@
raise ImportError("PARAM_TEST_JSONSCHEMA=1 but jsonschema not available.")
validate = None

now = datetime.datetime.now()
after_now = now + datetime.timedelta(days=1)

try:
import numpy as np
ndarray = np.array([[1,2,3],[4,5,6]])
npdt1 = np.datetime64(now)
npdt2 = np.datetime64(after_now)
except:
np, ndarray = None, None
np, ndarray, npdt1, npdt2 = None, None, None, None

np_skip = skipIf(np is None, "NumPy is not available")

try:
import pandas as pd
df1 = pd.DataFrame({'A':[1,2,3], 'B':[1.1,2.2,3.3]})
df2 = pd.DataFrame({'A':[1.1,2.2,3.3], 'B':[1.1,2.2,3.3]})
pdts1 = pd.Timestamp(now)
pdts2 = pd.Timestamp(after_now)
except:
pd, df1, df2 = None, None, None
pd, df1, df2, pdts1, pdts2 = None, None, None, None, None

pd_skip = skipIf(pd is None, "pandas is not available")

Expand All @@ -52,6 +59,8 @@ class TestSet(param.Parameterized):
e = param.List([1,2,3], class_=int)
f = param.List([1,2,3])
g = param.Date(default=datetime.datetime.now())
g2 = None if np is None else param.Date(default=npdt1)
g3 = None if pd is None else param.Date(default=pdts1)
h = param.Tuple(default=(1,2,3), length=3)
i = param.NumericTuple(default=(1,2,3,4))
j = param.XYCoordinates(default=(32.1, 51.5))
Expand All @@ -73,6 +82,20 @@ class TestSet(param.Parameterized):
y = None if np is None else param.Array(default=None)
z = None if pd is None else param.DataFrame(default=None, allow_None=True)
aa = param.Tuple(default=None, allow_None=True, length=1)
ab = param.CalendarDateRange(default=(
datetime.date(2020, 1, 1),
datetime.date(2021, 1, 1)
))
ac = param.DateRange(default=(
datetime.date(2020, 1, 1),
datetime.date(2021, 1, 1)
))
ad = param.DateRange(default=(
datetime.datetime(2020, 1, 1, 1, 1, 1, 1),
datetime.datetime(2021, 1, 1, 1, 1, 1, 1)
))
ae = None if np is None else param.DateRange(default=(npdt1, npdt2))
af = None if pd is None else param.DateRange(default=(pdts1, pdts2))


test = TestSet(a=29)
Expand Down Expand Up @@ -128,6 +151,23 @@ def test_serialize_date_class(self):
def test_serialize_date_instance(self):
self._test_serialize(test, 'g')

@np_skip
def test_serialize_date_numpy_class(self):
self._test_serialize(TestSet, 'g2')

@np_skip
def test_serialize_date_numpy_instance(self):
self._test_serialize(test, 'g2')
self._test_serialize(test, 'g')

@pd_skip
def test_serialize_date_pandas_class(self):
self._test_serialize(TestSet, 'g3')

@pd_skip
def test_serialize_date_pandas_instance(self):
self._test_serialize(test, 'g3')

def test_serialize_tuple_class(self):
self._test_serialize(TestSet, 'h')

Expand Down Expand Up @@ -194,6 +234,39 @@ def test_pandas_instance_serialization(self):
else:
self.assertTrue(getattr(test, pname).equals(deserialized[pname]))

def test_serialize_calendar_date_range_class(self):
self._test_serialize(TestSet, 'ab')

def test_serialize_calendar_date_range_instance(self):
self._test_serialize(test, 'ab')

def test_serialize_date_range_class(self):
self._test_serialize(TestSet, 'ac')

def test_serialize_date_range_instance(self):
self._test_serialize(test, 'ac')

def test_serialize_datetime_range_class(self):
self._test_serialize(TestSet, 'ad')

def test_serialize_datetime_range_instance(self):
self._test_serialize(test, 'ad')

@np_skip
def test_serialize_datetime_range_numpy_class(self):
self._test_serialize(TestSet, 'ae')

@np_skip
def test_serialize_datetime_range_numpy_instance(self):
self._test_serialize(test, 'ae')

@pd_skip
def test_serialize_datetime_range_pandas_class(self):
self._test_serialize(TestSet, 'af')

@pd_skip
def test_serialize_datetime_range_pandas_instance(self):
self._test_serialize(test, 'af')


class TestJSONSerialization(TestSerialization):
Expand Down