On Oct 13, 2019, at 14:42, David Mertz <[email protected]> wrote:
>
> I have definitely hit this difficulty many times. The part of the code that
> "just puts something in the collection" doesn't need to care conceptually
> about the kind of collection. Taking the data back out somewhere else more
> often needs to worry about order, efficiency, concurrency, etc.
>
> But as I see other comments, I think an external function makes more sense.
> Sure, list and set could grow a common method. But then what about deque or
> queue? What about the excellent third part sortedcontainers package? Or a
> Panda Series? Do all of these need to grow that same method?
>
> I think more flexible would be a callable that also provided a way to
> register how to "just put the item in the container." This could be expanded
> by users only as far as was useful to them.
>
> Sufficiently refined, I can imagine wanting such a thing in the collections
> module itself.
>
> So maybe an API like:
>
> just_add_it.register(set, set.add)
> just_add_it.register(list, list.append)
> just_add_it.register(Queue, Queue.put)
> just_add_it.register(MyCollection, lambda stuff, item: ...)
This is exactly what `singledispatch` already gives you:
from functools import singledispatch
@singledispatch
def just_add_it(collection, value):
raise TypeError(blah blah)
Now you can explicitly register methods like this:
just_add_it.register(set, set.add)
just_add_it.register(list, list.append)
just_add_it.register(Queue, Queue.put)
And, while you can do the same thing with lambda, you can also write it as a
decorator:
@just_add_it.register(MyCollection)
def _(stuff, item):
# ....
… which is more flexible and often more readable, especially for functions
whose whole point is a side effect.
And you can even use type annotations to make it even simpler:
@just_add_it.register
def _(stuff: MyCollection, item):
# ....
More generally, both you and Steve Jorgensen seem to be proposing a bunch of
things that already exist. It’s worth taking the time to figure out what’s
already there before suggesting changes.
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/5ZOJT6EEBETZVVJRSJ7GO2XADHPGHLCS/
Code of Conduct: http://python.org/psf/codeofconduct/