[Python-3000] [Python-Dev] dict.items as attributes [Was: The bytes type]

Greg Falcon veloso at verylowsodium.com
Wed Jan 17 14:38:03 CET 2007


On 1/16/07, Barry Warsaw <barry at python.org> wrote:
> I know Guido is against attribute syntax for dict.items and friends,
> and I agree with him for reasons I can't quite put my finger on.

I agree that making dict.items and friends into attributes feels
wrong.  I suspect it may be useful to put a finger on why.  The
discussion about hash() linked in PEP 3099 led to a set of guidelines
for when properties are inappropriate, and notably, none of these
guidelines apply here.

Two explanations given here so far don't seem to explain my aversion.
It shouldn't matter that views are complex objects; I have a gut
feeling, anyway, that datatype shouldn't be a factor.  Nor does it
seem to matter whether the implementation pre-allocates these views or
creates them on-demand, since views are stateless, and since either
approach has a cheap fixed cost.

After a bit of mulling it over, the best objection I can come up with
is this: views aren't "attributes" or "properties" of a dict object in
the plain-English sense of the term.  This might simply be a flawed
appeal to an overloaded word, but I think it captures my gut feeling
well.  A dictionary object contains keys and values, and those
*contents* can be said to be attributes of a dictionary.  Views are
just wrapper objects that expose those contents in interesting ways.

Along those lines: very recently at work I added a method to a class
to provide an iterator over its items in a non-standard order.
Although I often use 'property' as a decorator, it didn't even occur
to me to make that method an attribute.  It still doesn't feel as
though I should, even though it would be cheap and easy to return a
stateless object with an appropriate __iter__ method.

A second objection: Although this is a clever way of adding
forwards-compatibility to 2.6, the side effect that views are callable
is odd.  It's especially unintuitive that v() is synonymous with
list(v).  The existing stateless, sequence-proxying objects (like
xrange) don't behave that way, and it would be strange if they did.

Part of me suspects that if Python builtin types or library types made
bigger use of attributes, this proposal wouldn't seem so weird.  There
are many opportunities in the library to replace zero-arg, cheap,
side-effect-free methods with read-only attributes, but that hasn't
happened.  This sort of thing still isn't really idiomatic, and just
because Python 3 is a major version bump doesn't mean we *should*
change the idioms.

Greg F


More information about the Python-3000 mailing list