Efficient Wrappers for Instance Methods

Peter Otten __peter__ at web.de
Wed Feb 3 16:15:12 EST 2016


Sven R. Kunze wrote:

> Hi,
> 
> as you might have noticed, I am working on
> https://github.com/srkunze/xheap right now.
> 
> In order to make it even faster and closer to heapq's baseline
> performance, I wonder if there is a possibility of creating fast
> wrappers for functions.
> 
> 
> Please compare
> 
> 
https://github.com/srkunze/xheap/blob/ca56ac55269ce0bc7b61d28ba9ceb41e9075476a/xheap.py#L29
> 
https://github.com/srkunze/xheap/blob/ca56ac55269ce0bc7b61d28ba9ceb41e9075476a/xheap.py#L32
> 
> with
> 
> 
https://github.com/srkunze/xheap/blob/ca56ac55269ce0bc7b61d28ba9ceb41e9075476a/xheap.py#L44
> 
> 
> Why is it not possible to create a method from a function like I aliased
> replace with poppush?

The technical reason is that functions written in C don't implement the 
descriptor protocol. The bound method is created by invoking the __get__ 
method of the class attribute:

>>> from heapq import heappush
>>> class A: pass
... 
>>> def method(*args): print("invoked with", args)
... 
>>> a = A()
>>> m = method.__get__(a)
>>> m(42)
invoked with (<__main__.A object at 0x7f07194c29b0>, 42)
>>> n = heappush.__get__(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 
'__get__'
 
> If I am not completely mistaken, it saves 1 stack frame, right?
> 
> 
> Best,
> Sven





More information about the Python-list mailing list