Skip to content

Commit

Permalink
Allow empty data source in DataSourceMixin.
Browse files Browse the repository at this point in the history
  • Loading branch information
riga committed Aug 30, 2022
1 parent 0b8db6b commit 0ae6fbd
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 7 deletions.
30 changes: 23 additions & 7 deletions order/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,12 @@ class MyClass(od.DataSourceMixin):
The data source string for mc (``"mc"``).
.. py:classattribute:: allow_undefined_data_source
type: boolean
A configuration flag for this class that decides whether empty (*None*) data sources are
allowed. *False* by default.
.. py:attribute:: is_data
type: boolean
Expand All @@ -505,6 +511,9 @@ class MyClass(od.DataSourceMixin):
DATA_SOURCE_DATA = "data"
DATA_SOURCE_MC = "mc"

# whether the data source is allowed to be undefined / None
allow_undefined_data_source = False

copy_specs = []

def __init__(self, is_data=False):
Expand All @@ -522,24 +531,31 @@ def is_data(self):

@is_data.setter
def is_data(self, is_data):
if not isinstance(is_data, bool):
if is_data is None and self.allow_undefined_data_source:
self._is_data = None
elif isinstance(is_data, bool):
self._is_data = is_data
else:
raise TypeError("invalid is_data type: {}".format(is_data))

self._is_data = is_data

@property
def is_mc(self):
return not self.is_data
return None if self.is_data is None else (not self.is_data)

@is_mc.setter
def is_mc(self, is_mc):
if not isinstance(is_mc, bool):
if is_mc is None and self.allow_undefined_data_source:
self._is_data = None
elif isinstance(is_mc, bool):
self._is_data = not is_mc
else:
raise TypeError("invalid is_mc type: {}".format(is_mc))

self._is_data = not is_mc

@property
def data_source(self):
if self.is_data is None:
return None

return self.DATA_SOURCE_DATA if self.is_data else self.DATA_SOURCE_MC


Expand Down
14 changes: 14 additions & 0 deletions tests/test_mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,20 @@ def test_setters(self):
with self.assertRaises(TypeError):
c.is_mc = {}

def test_empty_source(self):
class C(DataSourceMixin):
allow_undefined_data_source = True

c = C(is_data=None)
self.assertIsNone(c.is_data)
self.assertIsNone(c.is_mc)
self.assertIsNone(c.data_source)

c.is_mc = True
self.assertFalse(c.is_data)
self.assertTrue(c.is_mc)
self.assertEqual(c.data_source, "mc")


class SelectionMixinTest(unittest.TestCase):

Expand Down

0 comments on commit 0ae6fbd

Please sign in to comment.