[Python-Dev] PEP 362 minor nits

Yury Selivanov yselivanov.ml at gmail.com
Wed Jun 20 15:01:23 CEST 2012


On 2012-06-20, at 4:30 AM, Steven D'Aprano wrote:

> On Tue, Jun 19, 2012 at 08:11:26PM -0400, Yury Selivanov wrote:
> 
>> So using the signature will be OK for 'Foo.bar' and 'Foo().bar', but
>> not for 'Foo.__dict__['bar']' - which I think is fine (since
>> staticmethod & classmethod instances are not callable)
> 
> There has been some talk on Python-ideas about making staticmethod and 
> classmethod instances callable.
> 
> Speaking of non-instance method descriptors, please excuse this silly 
> question, I haven't quite understood the implementation well enough to 
> answer this question myself. Is there anything needed to make 
> signature() work correctly with custom method-like descriptors such as 
> this?
> 
> http://code.activestate.com/recipes/577030-dualmethod-descriptor

Well, as Nick said -- the PEP way is to create a new Signature with
a first parameter skipped.

But in this particular case you can rewrite it (I'd say preferred way):

    class dualmethod:
        def __init__(self, func):
            self.func = func

        def __get__(self, instance, owner):
            if instance is None:
                return types.MethodType(self.func, owner)
            else:
                return types.MethodType(self.func, instance)

Or another way, using functools.partial:

    class dualmethod:
        def __init__(self, func):
            self.func = func

        def __get__(self, instance, owner):
            if instance is None:
                return functools.partial(self.func, owner)
            else:
                return functools.partial(self.func, instance)


Since 'MethodType' and 'partial' are supported by signature(), 
everything will work automatically (i.e. first argument will be 
skipped)

-
Yury


More information about the Python-Dev mailing list