Notation for intervals?
<p>I want to make a Python class for intervals of real numbers. Syntax most closely related to mathematical notation would be <code>Interval([a, b))</code> or, even better, <code>Interval[a, b)</code> to construct the interval of all real <code>x</code> satisfying <code>a &lt;= x &lt; b</code>.</p>

<p>Is it possible to construct a class that would handle this syntax? </p>

<p>It's impossible to "fix" syntactically invalid python by making a custom class.</p>

<p>I think the closest you can get to the mathematical interval notation in python is</p>

<pre><code>Interval('[a, b)')
</code></pre>

<p>This way becomes even more lightweight if you are passing intervals as arguments to a function and the function converts it's arguments to an appropriate type before using them. Example:</p>

<pre><code>def do_foo(interval, bar, baz):
    interval = Interval(interval)
    # do stuff

do_foo('[3,4)', 42, true)
</code></pre>

<p><a href="http://ideone.com/BXBeXi" rel="nofollow">Possible implementation</a>:</p>

<pre><code>import re

class Interval:
    def __init__(self, interval):
        """Initialize an Interval object from a string representation of an interval
           e.g: Interval('(3,4]')"""
        if isinstance(interval, Interval):
            self.begin, self.end = interval.begin, interval.end
            self.begin_included = interval.begin_included
            self.end_included = interval.end_included
            return
        number_re = '-?[0-9]+(?:.[0-9]+)?'
        interval_re = ('^\s*'
                       +'(\[|\()'  # opeing brecket
                       + '\s*'
                       + '(' + number_re + ')'  # beginning of the interval
                       + '\s*,\s*'
                       + '(' + number_re + ')'  # end of the interval
                       + '\s*'
                       + '(\]|\))'  # closing brecket
                       + '\s*$'
                      )
        match = re.search(interval_re, interval)
        if match is None:
            raise ValueError('Got an incorrect string representation of an interval: {!r}'. format(interval))
        opening_brecket, begin, end, closing_brecket = match.groups()
        self.begin, self.end = float(begin), float(end)
        if self.begin &gt;= self.end:
            raise ValueError("Interval's begin shoud be smaller than it's end")
        self.begin_included = opening_brecket == '['
        self.end_included = closing_brecket == ']'
        # It might have been batter to use number_re = '.*' and catch exeptions float() raises instead

    def __repr__(self):
        return 'Interval({!r})'.format(str(self))

    def __str__(self):
        opening_breacket = '[' if self.begin_included else '('
        closing_breacket = ']' if self.end_included else ')'
        return '{}{}, {}{}'.format(opening_breacket, self.begin, self.end, closing_breacket)

    def __contains__(self, number):
        if self.begin &lt; number &lt; self.end:
            return True
        if number == self.begin:
            return self.begin_included
        if number == self.end:
            return self.end_included
</code></pre>

python