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

Feature/7 interval initialization #8

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 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
30 changes: 30 additions & 0 deletions intervals/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,24 @@ def wrapper(self, arg):
return wrapper


class ClosedInterval(type):
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lets just name this as IntervalMeta. It would be strange if you initialize an open interval and its meta type is still 'ClosedInterval'.

"""
Supports initialization of intervals using square brackets and makes them
closed intervals.

eg.

IntInterval[1, 4] == IntInterval([1, 4])
"""
def __getitem__(self, bounds):
lower_inc = upper_inc = True
return self(bounds, lower_inc, upper_inc)


@total_ordering
class AbstractInterval(object):
__metaclass__ = ClosedInterval
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does not work on Python 3.3. See http://pythonhosted.org/six/#six.with_metaclass


step = None
type = None
parser = IntervalParser()
Expand Down Expand Up @@ -151,6 +167,20 @@ def __init__(
30

"""

# This if-block adds support for parentheses as open intervals.
# Note: If the interval is initialized with the parentheses with two
# objects of same type, eg.
# IntInterval(1, 4)
# the bounds and lower_inc are received of that type and
# upper_inc is None.
#
# eg.
# IntInterval(1, 4) == IntInterval((1, 4))
if type(bounds) == type(lower_inc) and not upper_inc:
bounds = (bounds, lower_inc)
lower_inc = upper_inc = None

self.lower, self.upper, self.lower_inc, self.upper_inc = (
self.parser(bounds, lower_inc, upper_inc)
)
Expand Down
6 changes: 6 additions & 0 deletions tests/test_initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ def test_supports_integers(self):
assert interval.lower_inc
assert interval.upper_inc

def test_uses_two_numbers_with_parentheses_as_open_interval(self):
assert IntInterval(1, 2) == IntInterval((1, 2))

def test_uses_two_numbers_with_square_brackets_as_closed_interval(self):
assert IntInterval[1, 2] == IntInterval([1, 2])

@mark.parametrize('number_range',
(
(3, 2),
Expand Down