Some syntactic sugar proposals

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Tue Nov 16 00:26:08 EST 2010


On Sun, 14 Nov 2010 22:39:05 -0800, Dmitry Groshev wrote:

> Here are some proposals. They are quite useful at my opinion and I'm
> interested for suggestions. It's all about some common patterns. First
> of all: how many times do you write something like
>     t = foo()
>     t = t if pred(t) else default_value
> ? 

Hardly ever. Not often enough to need special syntax for it.


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"?


t = foo()+bar()+baz() if pred(it) else baz()-foo()-bar()

What does "it" mean here?



> Second, I saw a lot of questions about using dot notation for a
> "object-like" dictionaries and a lot of solutions like this:
>     class dotdict(dict):
>         def __getattr__(self, attr):
>             return self.get(attr, None)
>         __setattr__= dict.__setitem__
>         __delattr__= dict.__delitem__
> why there isn't something like this in a standart library?


Because dot notation for dictionaries is not something we should 
encourage.



> 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!

Why do you say it's wrong? It's perfectly correct:

1 in range(1, 10)
=> returns True

1.5 in range(1, 10)
=> returns False

5 in range(1, 10)
=> returns True

10 in range(1, 10)
=> returns False

exactly as I expect for element testing in a half-open interval. So 
where's the problem? If you want interval testing, you need to perform an 
interval test, not an element test.


> 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.


If I write:

x in range(1, 10)

how do you expect the compiler to read my mind and know if I want the 
half-open interval or the closed interval?



-- 
Steven



More information about the Python-list mailing list