possible attribute-oriented class
steve at REMOVE-THIS-cybersource.com.au
Sat Sep 5 11:57:35 CEST 2009
On Fri, 04 Sep 2009 22:51:39 -0700, Ken Newton wrote:
> On Fri, Sep 4, 2009 at 9:49 PM, Steven
> D'Aprano<steve at remove-this-cybersource.com.au> wrote: ...
>>> The old discussion, the above link points to, shows that such a
>>> dot-accessible dict-like class is something that many people need and
>>> repeatedly implemet it (more or less perfectly) for themselves.
>> I think it's something which people copy from other languages because
>> that's what they're used to, not because they need it.
>> It's just a change in syntax. Whether you write x.key or x['key'] is a
>> matter of convenience. Attribute access is optimized for when you know
>> the key names at compile time, key access is optimized for when you
>> don't know the names until runtime. Compare:
>> # You know the key when you write the code. x.key versus x['key']
>> # You don't know the key until runtime. s = get_key()
>> getattr(x, s) versus x[s]
> I would think this is much more than just copy from other language
> styles or 'just' a syntax change -- the apparent widespread use would
> hint at a deeper need.
"Apparent" is the key word there. There are lots of people who *say* this
this useful functionality, but how many of them *actually* use it? And of
those who do use it, how many of them know what they're doing? There are
an awful lot of bad programmers out there.
If you do need such functionality, it's easy to implement. Here's one:
No comment, no votes.
Four comments, mostly negative, no votes.
To me, this seems like a superficially attractive idea which is actually
a bad idea, even when it's useful. Using a screwdriver as a chisel, or
crowbar is useful too, and I've done so myself, but it's still usually a
Key lookup and attribute access are superficially similar, and they're
implemented the same way in Python, but they're actually for different
conceptual purposes. Attributes are conceptually part of the object,
while key/values are conceptually data attached to the object. As a
general rule, if obj.x is an attribute, then every valid obj should have
an attribute x. But if obj['x'] is a key/value, then it is data-specific:
some instances will have an 'x' key, and some won't. Consequently,
obj.has_key('x') (better written these days as 'x' in obj) will be MUCH
more common than hasattr(obj, 'x').
For example, dict.clear has a special meaning shared by all dicts.
dict['clear'] does not. You confuse the two at your peril.
More information about the Python-list