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>You can't change Python's existing syntax rules (without changing the whole language), but you can get usably close to what you want:</p>

<pre><code>class Interval(object):
    def __init__(self, left_bracket, a, b, right_bracket):
        if len(left_bracket) !=1 or left_bracket not in '[(':
            raise ValueError(
                'Unknown left bracket character: {!r}'.format(left_bracket))
        if len(right_bracket) !=1 or right_bracket not in '])':
            raise ValueError(
                'Unknown right bracket character: {!r}'.format(right_bracket))

        if a &lt; b:
            self.lower, self.upper = a, b
        else:
            self.lower, self.upper = b, a

        self.left_bracket, self.right_bracket = left_bracket, right_bracket

        if left_bracket == '[':
            if right_bracket == ']':
                self._contains = (
                    lambda self, val: self.lower &lt;= val &lt;= self.upper)
            else:
                self._contains = (
                    lambda self, val: self.lower &lt;= val &lt;  self.upper)
        else:
            if right_bracket == ']':
                self._contains = (
                    lambda self, val:  self.lower &lt; val &lt;= self.upper)
            else:
                self._contains = (
                    lambda self, val:  self.lower &lt; val &lt;  self.upper)

    __contains__ = lambda self, val: self._contains(self, val)

    def __str__(self):
        return '{}{}, {}{}'.format(self.left_bracket, self.lower, self.upper,
                                   self.right_bracket)

    def __repr__(self):
        return '{}({!r}, {}, {}, {!r})'.format(self.__class__.__name__,
                self.left_bracket, self.lower, self.upper, self.right_bracket)

if __name__ == '__main__':
    interval1 = Interval('[', 1, 3, ']')  # closed interval
    interval2 = Interval('[', 1, 3, ')')  # half-open interval

    print('{} in {}? {}'.format(3, interval1,  3 in interval1))
    print('{} in {}? {}'.format(3, interval2,  3 in interval2))
</code></pre>

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>3 in [1, 3]? True
3 in [1, 3)? False
</code></pre>

<p>Note: The <code>a</code> and <code>b</code> arguments can be any type that can be compared.</p>

python