Some syntactic sugar proposals

Dmitry Groshev lambdadmitry at gmail.com
Wed Dec 1 18:18:32 EST 2010


On Nov 22, 2:21 pm, Andreas Löscher <andreas.loesc... at s2005.tu-
chemnitz.de> wrote:
> >     if x in range(a, b): #wrong!
> > it feels so natural to check it that way, but we have to write
> >     if a <= x <= b
> > I understand that it's not a big deal, but it would be awesome to have
> > some optimisations - it's clearly possible to detect things like that
> > "wrong" one and fix it in a bytecode.
>
> You can implement it yourself:
>
> class between(object):
>         def __init__(self, a,b):
>                 super(crang, self).__init__()
>                 self.a=a
>                 self.b=b
>         def __contains__(self, value):
>                 return self.a <= value <= self.b
>
> >>> 12.45 in between(-100,100)
>
> true
>
> But do you need
>
> a <  x <  b
> a <= x <  b
> a <= x <= b or
> a <  x <= b ?
>
> Sure, you could set a new parameter for this, but the normal way is not
> broken at all.
>
> Best

Of course there are better ways to do this. Your "between", standart
comparisons and so, but expressing this as "i in range(a, b)" is just
intuitive and declarative.
Here is a fresh example of what I meant by my first proposal. You need
to build a matrix like this:
2 1 0 ...
1 2 1 ...
0 1 2 ...
...
... 1 2 1
... 0 1 2
You could do this by one-liner:
[[(2 - abs(x - y)) if it > 0 else 0 for x in xrange(8)] for y in
xrange(8)]
...but in reality you should write something like this:
[[(lambda t: t if t > 0 else 0)(2 - abs(x - y)) for x in xrange(8)]
for y in xrange(8)]
or this
[[(2 - abs(x - y)) if (2 - abs(x - y)) > 0 else 0 for x in xrange(8)]
for y in xrange(8)]
or even this
def foo(x, y):
    if abs(x - y) == 0:
        return 2
    elif abs(x - y) == 1:
        return 1
    else:
        return 0
[[foo(x, y) for x in xrange(8)] for y in xrange(8)]
It's not THAT matter, but it's just about readability and shortness in
some cases.



More information about the Python-list mailing list