Set/Get attribute syntatic sugar

Terry Hancock hancock at anansispaceworks.com
Tue Jun 28 23:37:58 EDT 2005


On Tuesday 28 June 2005 07:07 pm, Elmo Mäntynen wrote:
> Peter Hansen wrote:
> > Заур Шибзухов wrote:
> >> There is a syntactic sugar for item access in
> >> dictionaries and sequences:
> >> o[e] = v <-> o.__setitem__(e, v)
> >> o[e] <-> o.__getitem__(e)
> >>
> >> where e is an expression.
> >>
> >> There is no similar way for set/get attribute for objects.
> >> If e is a given name, then      o.e = v <-> o.__setattr__(e, v)
> >> o.e <-> o.__getattr__(e)
> >>
> >> Anybody thought about this issue?

I'm pretty sure it's been discussed. Javascript unifies the concepts of
dictionary access and object attribute access into the single concept
of "associational array" (there are some limitations to the Javascript
version, so they aren't really equivalent, but for simple cases they
often are).

In Javascript, the expression

a['b']

means the same thing as

a.b

> > Perhaps not, but now that you've pointed it out they've taken the time
> > machine back and fixed the problem before it arose:
> 
> Maybe funny, but a bit too cocky for my taste. Robert kern is propably
> right about what he really meant so don't be too hasty in the future,
> right?). Looking at his code example I got the picture that he's of the
> kind that could come up with something useful. So either he's
> right(which I think is the case), or it's just the kind of silly mistake
> all of us sometimes make. I sure think some one should look in to this
> suggestion.

Could be, but I think the absence of  "sugar" in this situation is
at least semi-intentional.  We already have dictionary access for
when this type of situation is needed.  And if you really want an
object that permits either type of access --- that is, for which
dictionary access and attribute access are the same --- it is not
difficult to create one.

OTOH, if it were automatic, it would tend to erase any distinction
between the two concepts.  Stylistically, dictionaries are the "right"
thing to use when the elements are going to be very fluid, whereas
objects are expected to have more or less fixed attribute and method
interfaces.  Making "access to attribute by string name" more
difficult than "access to dictionary value by string key" is one way
to encourage the distinction.

And, really, when you do need it, __getattr__ / __setattr__ aren't
really *that* difficult to use.

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list