Some syntactic sugar proposals

Dmitry Groshev lambdadmitry at gmail.com
Mon Nov 15 07:39:05 CET 2010


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

x in range optimisation
dot dict access
foo() if foo() else bar()



More information about the Python-list mailing list