On 29.07.2014 15:35, Steven D'Aprano wrote:
On Mon, Jul 28, 2014 at 11:15:44PM -0700, Andrew Barnert wrote:
On Monday, July 28, 2014 8:34 PM, Steven D'Aprano <steve@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?
[snip]
In the hybrid form I'm referring to, the first argument provided is the class when called from the class, and the instance when called from an instance. Imagine it written in pure Python like this:
class dict: @hybridmethod def merged(this, *args, **kwargs): if isinstance(this, type): # Called from the class new = this() else: # Called from an instance. new = this.copy() for arg in args: new.update(arg) new.update(kwargs) return new [snip]
I really like the semantics of that. This allows for concise, and in my opinion, clearly readable code. Although I think maybe one should have two separate methods: the class method being called ``merged`` and the instance method called ``merged_with``. I find result = somedict.merged(b, c) somewhat less clear than result = somedict.merged_with(b, c) regards, jwi