Skip to content

Commit

Permalink
Fix for Bug #5, daterange not accepting subclasses of date
Browse files Browse the repository at this point in the history
  • Loading branch information
runfalk committed Mar 7, 2017
1 parent b8607ae commit 867f132
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
8 changes: 8 additions & 0 deletions doc/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ Version are structured like the following: ``<major>.<minor>.<bugfix>``. The
first `0.1` release does not properly adhere to this. Unless explicitly stated,
changes are made by `Andreas Runfalk <https://github.com/runfalk>`_.

Version 0.4.0
-------------
Released on <unreleased>

- Fixed :class:`~spans.types.daterange` not accepting subclasses of ``date``
(`bug #5 <https://github.com/runfalk/spans/issues/5>`_)


Version 0.3.0
-------------
Released on 26th August, 2016
Expand Down
10 changes: 10 additions & 0 deletions spans/tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,16 @@ def test_len(self):
with self.assertRaises(ValueError):
len(daterange())

def test_bug5_date_subclassing(self):
"""
`Bug #5 <https://github.com/runfalk/spans/issues/5>`
"""

class DateSubClass(date):
pass

daterange(DateSubClass(2000, 1, 1))


class TestStrRange(TestCase):
def test_last(self):
Expand Down
20 changes: 18 additions & 2 deletions spans/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -938,6 +938,22 @@ def prev(cls, curr):
else:
return curr[:-1] + uchr(ord(curr[-1]) - 1)


def _is_valid_date(obj, accept_none=True):
"""
Check if an object is an instance of, or a subclass deriving from, a
``date``. However, it does not consider ``datetime`` or subclasses thereof
as valid dates.
:param obj: Object to test as date.
:param accept_none: If True None is considered as a valid date object.
"""

if accept_none and obj is None:
return True
return isinstance(obj, date) and not isinstance(obj, datetime)


class daterange(discreterange, offsetablerange):
"""
Range that operates on ``datetime.date``.
Expand All @@ -961,14 +977,14 @@ class daterange(discreterange, offsetablerange):
step = timedelta(days=1)

def __init__(self, lower=None, upper=None, lower_inc=None, upper_inc=None):
if lower is not None and type(lower) is not date:
if not _is_valid_date(lower, accept_none=True):
raise TypeError((
"Invalid type for lower bound '{lower_type.__name__}'"
" expected '{expected_type.__name__}'").format(
expected_type=self.type,
lower_type=lower.__class__))

if upper is not None and type(upper) is not date:
if not _is_valid_date(upper, accept_none=True):
raise TypeError((
"Invalid type for upper bound '{upper_type.__name__}'"
" expected '{expected_type.__name__}'").format(
Expand Down

0 comments on commit 867f132

Please sign in to comment.