Frankly, I don't think an "as dict" protocol is worth it, but if others did
think so, we could:

define a new dunder:  __as_mapping__

(I'm using "mapping", rather than "dict", to allow duck typing)

Then the built-in dict() constructor would:

check for an __as_mapping__ dunder:
  -- if there, it would call it and expect to get a mapping back that it
could turn into a dict.
  -- if not, it would go through its current process

( you could perhaps specify a subset of the mapping interface -- maybe all
you'd need is .items(), for instance -- so it would actually return an
iterator of key-value pairs. after all, dict() can already consume that.)

Meanwhile, any other code that wants to could also use the __as_mapping__
dunder to be able to work with an object as though it were a mapping, even
if that isn't its usual interface.

As far as I can see, the only downside of this is that it would means a new
standard dunder, which is a substantial downside, as (I think) it
essentially adds overhead in all sorts of places, plus ads "One more
protocol" to a language already ripe with protocols.

At least that's the message I got when I suggested adding a dunder for a
sorting key method.

-CHB


On Thu, May 9, 2019 at 10:13 AM Ricky Teachey <ri...@teachey.org> wrote:

> Another difficulty I just thought of:
>     - a NT class- and a dcls, for that matter- could also be an iterable
> two-tuples that would currently get dict-ified using iteration. So a
> precedence rule- does iter() win? Or the asdict functions?- would be needed
> for this, too.
>
> The answer to that seems a lot less obvious to me (compared to the mapping
> protocol), since iterating k-v pairs is relying on a bit of a side effect,
> but that side effect has probably existed since the dict was created.
> _______________________________________________
> Python-ideas mailing list
> Python-ideas@python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>


-- 
Christopher Barker, PhD

Python Language Consulting
  - Teaching
  - Scientific Software Development
  - Desktop GUI and Web Development
  - wxPython, numpy, scipy, Cython
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to