[Python-ideas] adding dictionaries
Andrew Barnert
abarnert at yahoo.com
Tue Jul 29 08:15:44 CEST 2014
On Monday, July 28, 2014 8:34 PM, Steven D'Aprano <steve at pearwood.info> wrote:
[snip]
> * when called from a class, it should behave like a class method:
> MyMapping.merged(a, b, c) should return an instance of MyMapping;
>
> * but when called from an instance, it should behave like an instance
> method, with self included in the chain of mappings to merge:
> a.merged(b, c) rather than a.merged(a, b, c).
>
>
> I have a descriptor type which implements the behaviour from the last
> two bullet points, so from a technical standpoint it's not hard to
> implement this. But I can imagine a lot of push-back from the more
> conservative developers about adding a *fourth* method type (even if it
> is private) to the Python builtins, so it would take a really compelling
> use-case to justify adding a new method type and a new dict method.
>
> (Personally, I think this hybrid class/instance method type is far more
> useful than staticmethod, since I've actually used it in production
> code, but staticmethod isn't going away.)
How is this different from a plain-old (builtin or normal) method?
>>> class Spam:
... def eggs(self, a):
... print(self, a)
>>> spam = Spam()
>>> Spam.eggs(spam, 2)
<__main__.Spam object at 0x106377080> 2
>>> spam.eggs(2)
<__main__.Spam object at 0x106377080> 2
>>> Spam.eggs
<function __main__.eggs>
>>> spam.eggs
<bound method Spam.eggs of <__main__.Spam object at 0x106377080>>
>>> s = {1, 2, 3}
>>> set.union(s, [4])
{1, 2, 3, 4}
>>> s.union([4])
{1, 2, 3, 4}
>>> set.union
<method 'union' of 'set' objects>
>>> s.union
<function union>
This is the way methods have always worked (although the details of how they worked under the covers changed in 3.0, and before that when descriptors and new-style classes were added).
More information about the Python-ideas
mailing list