Turning builtin functions into methods.

Jacek Generowicz jacek.generowicz at cern.ch
Tue Dec 9 10:41:52 CET 2003


Functions defined in Python have type types.FunctionType, and are
descriptors whose __get__ method turns them into bound or unbound
methods. Functions defined in extension modules have type
types.BuiltinFunctionType, and have no __get__ method. Adding them as
attributes to classes and calling them through an instance of the
class does not result in them being called as methods: self is lost.

What's the simplest way of getting around this ?

Some background: I'm trying to speed up my application by recoding, in
C, the Python functions which are being called in my inner loops. I
have a number of classes which have a single method being called in
the inner loops, so, rather than recoding the whole class, I'd like to
recode only the relevant method, and glue it onto the class, like this

  class foo:
      def this(self, ...):
          ...
      def that(self, ...):
          ...
      
  import speedup

  foo.the_other = speedup.the_other

where the_other is implemented in C, but is equivalent to

  def the_other(self, ...):
      ...


Any suggestions ?

Thanks,



PS. I'm a bit disappointed that Python makes this distinction between
functions defined in extension modules, and ones defined in pure
Python, but I guess that there are good practical reasons for it.




More information about the Python-list mailing list