Some syntactic sugar proposals
Mark Wooding
mdw at distorted.org.uk
Mon Nov 15 07:28:46 EST 2010
Dmitry Groshev <lambdadmitry at gmail.com> writes:
> First of all: how many times do you write something like
> t = foo()
> t = t if pred(t) else default_value
> ? Of course we can write it as
> t = foo() if pred(foo()) else default_value
> but here we have 2 foo() calls instead of one. Why can't we write just
> something like this:
> t = foo() if pred(it) else default_value
> where "it" means "foo() value"?
How about
t = (lambda y: y if pred(y) else default_value)(foo(x))
You could even package the lambda into a named function if you get bored
of typing or your aesthetic senses are offended.
> And the third. The more I use python the more I see how "natural" it
> can be. By "natural" I mean the statements like this:
> [x.strip() for x in reversed(foo)]
> which looks almost like a natural language. But there is some
> pitfalls:
> 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
This, I think, is your error. The test `x in range(a, b)' means the
same as `a <= x < b' (only in Python 2 it builds a list and then throws
it away again). Such half-open intervals turn out to be what you want
most of the time, and I think you'll avoid many bugs if you embrace them
rather than trying to cling to the fully-closed intervals above.
Python very definitely made the right decision to use half-open
intervals pervasively, e.g., for `rangeand 'in sequence slicing. It's a
bad idea to fight against it.
Advantages of half-open intervals [a, b):
* The number of elements is exactly b - a; closed intervals contain an
extra element which is often forgotten.
* They compose and split nicely: if a <= c <= b then [a, b) is exactly
the disjoint union of [a, c) and [c, b).
* Sums over these intervals are often better behaved; indeed, there's
a rather pretty analogy between sums on half-open intervals and
definite integrals which is lost if you use closed intervals. (The
above two observations are special cases of this one.) See Concrete
Mathematics (Graham, Knuth, Patashnik) for more on this.
* It's easy to express an empty interval. You can't do that if you
work entirely with closed intervals, but empty sets are an important
boundary case and it's annoying to have to handle them separately.
-- [mdw]
More information about the Python-list
mailing list