[Python-ideas] Anonymous namedtuples
Steven D'Aprano
steve at pearwood.info
Tue Apr 19 22:48:11 EDT 2016
On Tue, Apr 19, 2016 at 08:47:13PM +0000, Joseph Martinot-Lagarde wrote:
> > SimpleNamespace is neither a sequence nor a mapping.
> >
> I don't know the exact definition of a mapping, but to me SimpleNamespace is
> like a dict with restricted keys (valid attributes only) and a nicer syntax.
> `my_dict["key"]` is roughly equivalent to `my_namespace.key`.
That is (I believe) how Javascript and PHP treat it, but they're not
exactly the best languages to emulate, or at least not blindly.
Attributes and keys represent different concepts. Attributes represent
an integral part of the object:
dog.tail
me.head
car.engine
book.cover
while keys represent arbitrary (or nearly so) data associated with some
data collection:
books['The Lord Of The Rings']
kings['Henry VIII']
prisoner[239410]
colours['AliceBlue']
They don't just use different syntaxes, they have different purposes,
and while it is tempting to (mis)use the shorter attribute syntax for
key lookups:
colours.AliceBlue
it is risky to conflate the two. Suppose you have a book called
"update" (presumably a book of experimental poetry by somebody who
dislikes uppercase letters):
books.update
Either the key shadows the update method, or the method shadows the
book, or you get an error. All of these scenarios are bad.
I'd consider giving Python an alternate key-lookup syntax purely as
syntactic sugar:
colours~AliceBlue # sugar for colours['AliceBlue']
books~update # books['update']
before I would consider adding a standard library class that conflates
attribute- and key-lookup. If people want to do this in their own code
(and I do see the attraction, even if I think it is a bad idea), so be
it, but the standard library shouldn't encourage it.
--
Steve
More information about the Python-ideas
mailing list