Some syntactic sugar proposals

Dmitry Groshev lambdadmitry at gmail.com
Mon Nov 15 04:27:02 EST 2010


On Nov 15, 12:03 pm, alex23 <wuwe... at gmail.com> wrote:
> On Nov 15, 5:50 pm, Dmitry Groshev <lambdadmi... at gmail.com> wrote:
>
> > On Nov 15, 10:30 am, alex23 <wuwe... at gmail.com> wrote:
> > > 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.
>
> That's a gross oversimplification that tends towards wrong:
>
> >>> class C(object):
>
> ...   def __init__(self):
> ...     self._x = None
> ...   @property
> ...   def x(self): return self._x
> ...   @x.setter
> ...   def x(self, val): self._x = val
> ...>>> c = C()
> >>> c.x = 1
> >>> c.x
> 1
> >>> c.__dict__['x']
>
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> KeyError: 'x'
>
> But my concern has _nothing_ to do with the implementation detail of
> how objects hold attributes, it's solely over the clarity that comes
> from being able to visually tell that something is an object vs a
> dictionary.

Oh, now I understand you. But this "dotdict" (or "bunch") things don't
break anything. You still need to use it explicitly and it is very
useful if you need to serialize some JSON data about some entities.
    s = """[{"name": "Jhon Doe", "age": "12"}, {"name": "Alice",
"age": "23"}]"""
    t = map(dotdict, json.loads(s))
    t[0] #{'age': '12', 'name': 'Jhon Doe'}
    t[0].age #'12'
Of course you can do this with namedtuple, but in fact this isn't a
tuple at all. It's a list of entities.

> > > 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.
>
> So you want this:
>
>   if x in range(1,10):
>
> ...to effectively emit the same bytecode as a chained comparison while
> this:
>
>   for x in range(1,10):
>
> ...produces a list/generator?
>
> Never going to happen. "Special cases aren't special enough to break
> the rules." The standard form for chained comparisons can handle far
> more complex expressions which your 'in' version could not: 0 <= min
> <= max <= 100

I know about chained comparisons, thanks. It's not about them. It's
about bytecode optimisation. But maybe you are right about "Special
cases aren't special enough to break the rules". I kinda forgot that :)



More information about the Python-list mailing list