Some syntactic sugar proposals

Dmitry Groshev lambdadmitry at
Mon Nov 15 08:50:33 CET 2010

On Nov 15, 10:30 am, alex23 <wuwe... at> wrote:
> On Nov 15, 4:39 pm, Dmitry Groshev <lambdadmi... at> wrote:
> > 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"?
> Could you provide an actual use case for this. This seems weird to me:
> you're creating an object, testing the object, then possibly throwing
> it away and using a default instead. Are you sure you can't
> restructure your code as such:
>    t = foo(x) if <text on x> else default

Sure. Let's pretend you have some string foo and compiled regular
expression bar.
Naive code:
    t = bar.findall(foo)
    if len(t) < 3:
        t = []
Code with proposed syntactic sugar:
    t = bar.findall(foo) if len(it) > 2 else []

> > 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?
> Personally, I like keeping object attribute references separate from
> dictionary item references.
Your Python doesn't - dot notation is just a sugar for __dict__ lookup
with default metaclass.

> This seems more like a pessimisation to me: your range version
> constructs a list just to do a single container check. That's a _lot_
> more cumbersome than two simple comparisons chained together.
By "wrong" I meant exactly this. I told about "compiler" optimisation
of statements like this so it would not construct a list.

More information about the Python-list mailing list