Using function parameters to determine method kind

Lenard Lindstrom len-1 at telus.net
Tue Apr 6 01:35:46 EDT 2004


Michele Simionato <michele.simionato at poste.it> wrote:
>Lenard Lindstrom <len-1 at telus.net> wrote in message
> news:<4qrzym6e.fsf at telus.net>...
>> I was wondering if anyone has suggested having Python determine
>> a method's kind from its first parameter.
...
>I find relaying on tbe parameter name to specify the kind of method
>to be rather fragile. It works most times but not always. What about
>inner classes for instance?
Do you mean:
  from dparams import Object
  class A(Object):
      class B(Object):
          def __init__(self, x): self.x = x
  b=A.B(x)
 ?
Class A.B is not affected. Parameter checking only happens for
instances of type function. Other callables have to be or
use descriptors to be anything other than static. As for B's
methods, parameter checking works just fine. My module is
more of a demonstration than a practical solution anyway.
I would suggest a different approach for implementing
parameter checking in the python interpreter.

> Also, there are situations where you want
>a method to work both with instances and classes, so do you want to
>use self or cls?
I can only imagine one way to do this now, wrap the function in a
descriptor.

>>> from dparams import Object
>>> from types import MethodType
>>> class bimethod(Object):
... 	def __init__(self, f): self.f=f
... 	def __get__(self, o, t):
... 		if o is None: return MethodType(self.f, t, type(t))
... 		return MethodType(self.f, o, t)
... 	
>>> class A(Object):
... 	def bi(x): return x
... 	bi=bimethod(bi)
... 	
>>> A.bi()
<class '__main__.A'>
>>> A().bi()
<__main__.A object at 0x0119C1B0>

Descriptors are unaffected by the function's parameters, so the first
parameter can be anything you want. If I am not mistaken, the only
methods other that __new__  that currently work without descriptors
are instance methods. Is it not good form for instance methods to
start with 'self' anyways? (except maybe for a metaclass's __init__,
but this is a special case)

>I support PEP 318 also because this will kill home grown hacks (including
>my own) to provide this kind of functionality.
This is a good PEP. It would complement the use of parameters.

>I am also waiting for a better "super" but it seems nobody is talking 
>about it.
I gave it a try by changing the type argument passed to a descriptor's
__get__ method, but it required a rewritten classmethod of course.

Lenard Lindstrom
<len-l at telus.net>





More information about the Python-list mailing list