Storing objects required by functions.
Bengt Richter
bokr at oz.net
Tue Dec 30 23:07:01 EST 2003
On Wed, 31 Dec 2003 04:04:47 +0200, Christos "TZOTZIOY" Georgiou <tzot at sil-tec.gr> wrote:
>On 31 Dec 2003 00:08:47 GMT, rumours say that bokr at oz.net (Bengt
>Richter) might have written:
>
>>The other way is to take advantage of functions' roles as decriptors and the mechanism that
>>makes bound methods with a self as the first arg, but the rest apparently normal. I.e,
>>we can put the r parameter in the place of self (not specifically tested)
>>
>> def uses_self(r, x):
>> pass
>> uses_self = uses_self.__get__(re.compile("..."))
>
>It's much more general to use new.instancemethod. See:
I think I did use new.instancemethod, through another door ;-)
>>> def uses_self(r, x):
... pass
...
>>> import re
>>> uses_self = uses_self.__get__(re.compile("..."))
>>> type(uses_self)
<type 'instancemethod'>
>>> myim = type(uses_self)
>>> myim
<type 'instancemethod'>
>>> import new
>>> myim is new.instancemethod
True
;-)
>>> def foo(self, *args, **kw): print 'self=%r, args=%r, kw=%r'%(self, args, kw)
...
>>> myim(foo, 'dummy self', object) # object per your usage
<bound method object.foo of 'dummy self'>
>>> foom = myim(foo, 'dummy self', object) # object per your usage
>>> foom(1,2,3,hi='Hello')
self='dummy self', args=(1, 2, 3), kw={'hi': 'Hello'}
I didn't make voodoo out of it though. Interesting, but all that nested
calling at call-time seems like it would make for a performance hit? Unless maybe it is
all packed up in slots that C can get to very fast??
>
>def voodoo(function, *its_arguments):
> from new import instancemethod
> def child(function, first_argument, *rest_of_arguments):
> if rest_of_arguments:
> return child(
> instancemethod(function, first_argument, object),
> *rest_of_arguments
> )
> else:
> return instancemethod(function, first_argument, object)
> return child(function, *its_arguments)
>
>The import statement is in the voodoo just for completeness including it
>here.
>The function above recurses in order to allow stuff like:
>
>getter = voodoo(getattr, my_object, "its_attribute")
>
>or the more modern
>
>getter = voodoo(operator.itemgetter("its_attribute"), my_object)
>
>and similarly
>
>setter = voodoo(operator, my_object, "its_attribute")
>
>allowing
>
>setter(value)
>
>at good speeds.
>
>
>I have a module predicates.py defining All and Any classes for
>iterables, and the trick above plus itertools allows *some* operations
>to run faster than correspondent python code...
Interesting. Gotta go.
Regards,
Bengt Richter
More information about the Python-list
mailing list