importing a method

Alex Martelli aleax at mail.comcast.net
Mon Nov 28 22:01:59 EST 2005


Flavio <fccoelho at gmail.com> wrote:

> > If you have a function f and want to make an instancemethod out of it,
> > you can simply call f.__get__(theinstance, theclass) and that will build
> > and return the new instancemethod you require.
> 
> I think that
> 
> f.show = MethodType(show,f)
> 
> is less cryptic than  f.__get__(instance, class)

Hmmm, we're using different identifiers here for the same purposes,
making direct comparisons difficult.  Using clear identifiers in every
case, and avoiding keywords, we'd have something like:

from types import MethodType
instance.show = MethodType(show, instance, aclass)

versus

instance.show = show.__get__(instance, aclass)

[[you do need to pass the class if you want the repr of instance.show to
look nice, and this applies equally to both cases]].

I guess that instantiating a type (here, instancemethod) by calling it
with appropriate arguments is the "normal" approach, and calling
MethodType has the further advantage of working with different types as
the callable (first argument), not just functions.  The advantage of
__get__ is only polymorphism on different descriptor types, but that
looks rather less important.  So, "cryptic" apart (an issue on which one
could debate endlessly -- I'd argue that descriptors should be well
familiar by the time one starts generating methods on the fly;-),
calling MethodType does cover a wider range of uses.


Alex



More information about the Python-list mailing list