473,785 Members | 2,154 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Black Magic - Currying using __get__

Wow - Alex Martelli's 'Black Magic' Pycon notes
http://www.python.org/pycon/2005/pap...c05_bla_dp.pdf

include this gem:
Functions 'r descriptors
def adder(x, y): return x + y
add23 = adder.__get__(2 3)
add42 = adder.__get__(4 2)
print add23(100), add42(1000)
123 1042


This means that you can do (left) currying without a separate curry function
(Of course, google reveals that the idea has been discussed before,
http://mail.python.org/pipermail/pyt...er/038933.html)
Although it's less flexible than a general curry function, 'method currying' is
much faster, e.g., compare two functions for tail-filtering an iterator:

def filtertail(op, iterable):
"""Recursiv ely filter the tail of an iterator, based on its head
Useful for succinct (though not very fast) implementations
of sieve of eratosthenes among other"""
iterator = iter(iterable)
while 1:
head = iterator.next()
yield head
iterator = it.ifilter(curr y(op,Missing,he ad), iterator)

def filtertail2(op, iterable):
"""An alternative to filtertail, using Alex Martelli's observation
that functions are descriptors. Will not work for built-in
functions that lack a __get__ method"""
iterator = iter(iterable)
opcurry = op.__get__
while 1:
head = iterator.next()
yield head
iterator = it.ifilter(opcu rry(head), iterator)

using these generator functions, a Sieve of Eratosthenes can be written as:

primes = list(filtertail (operator.mod, xrange(2,N)))
or
primes = list(filtertail 2(lambda head, tail: tail % head, xrange(2,N)))

but the second version, using 'method currying' is 4 times the speed, despite
not using the stdlib operator.mod function

def timethem(N):
import time
t1 = time.clock()
p = list(filtertail (op.mod, xrange(2,N)))
t2 = time.clock()
p = list(filtertail 2(lambda head, tail: tail % head, xrange(2,N)))
t3 = time.clock()
return t2-t1, t3-t2
timethem(10000) (3.833199750247 5588, 0.7960575994993 6328) timethem(100000 ) (240.6815100801 9186, 61.818026872130 304)


of course, neither version is anywhere near the most efficient Python
implementation - this is a comparison of currying, not sieving.
BTW, here's the curry function I used (it could probably be faster; I'm not sure
what/where the future stdlib version is)
Missing = Ellipsis
def curry(*cargs, **ckwargs):
fn, cargs = cargs[0], cargs[1:]
if cargs[0] is Missing:
while cargs[0] is Missing: # rightcurry
cargs = cargs[1:]
def call_fn(*fargs, **fkwargs):
d = ckwargs.copy()
d.update(fkwarg s)
return fn(*(fargs+carg s),**d)
name = "%s(...,%s) " % (fn.__name__, ",".join(repr(i ) for i in cargs))
else:
def call_fn(*fargs, **fkwargs):
d = ckwargs.copy()
d.update(fkwarg s)
return fn(*(cargs + fargs), **d)
name = "%s(%s,...) " % (fn.__name__, ",".join(repr(i ) for i in cargs))
call_fn.func_na me = name
call_fn.curry = True
return call_fn

Michael

Jul 18 '05 #1
0 1725

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2521
by: Rico Huijbers | last post by:
Hello, I'd like to know if it's possible to curry a function in PHP? That is, is there some built-in mechanism for it, or is it possible to create a function that does the currying? I've tried something myself, and come up with the following: ---
2
1730
by: Shalabh Chaturvedi | last post by:
Almost everwhere the descriptor protocol is mentioned, it specifies __get__(obj, typ=None). Why is a default value needed for the second argument? In which case does Python call a descriptor without a second argument? Thanks, Shalabh
5
3049
by: Kenneth McDonald | last post by:
Now that I'm back to Python and all the new (to me) cool features, I find I'm using properties a lot, i.e. I'm defining: foo = property(fset=..., fget=...) for a number of properties, in many of my classes. I'm not using them for anything performance critical yet, but could see myself doing so in the future. Can anyone comment on the performance costs associated with properties vs. simple attribute lookup?
9
2760
by: Lenard Lindstrom | last post by:
I was wondering if anyone has suggested having Python determine a method's kind from its first parameter. 'self' is a de facto reserved word; 'cls' is a good indicator of a class method ( __new__ is a special case ). The closest to this I could find was the 2002-12-04 posting 'metaclasses and static methods' by Michele Simionato. The posting's example metaclass uses the method's name. I present my own example of automatic method kind...
2
2060
by: Jan Burgy | last post by:
Hi everyone, I am trying to convince my managers that python can replace the outdated and soon no-longer maintained proprietary system (Tool for Calculator Design) we use here. In order to achieve this, I need to analyze python code which will look somethink like this: def foo(arg_dict): return arg_dict + bar(arg_dict)
0
1102
by: John Perks and Sarah Mount | last post by:
I'm talk from the point of view of descriptors. Consider a.x = lambda self:None # simple function When a.x is later got, what criterion is used to see if a class (and so the func would have __get__(None, a) called on it)? Pre-metaclasses, one might assume it was isinstance(a, (types.TypeType, types.ClassType))
19
5172
by: youpak2000 | last post by:
Are MAGIC numbers always bad? Using magic numbers (constant numbers) in programs are generally considered a bad programming practice, and it's recommended that to define constants in single, visible place in a header file. My question is that is there any situation where using magic numbers is not necessarily a bad thing? lets say that we want to initialize some private variables in a class using some constant default numbers, can we...
16
2608
by: per9000 | last post by:
Hi, I recently started working a lot more in python than I have done in the past. And I discovered something that totally removed the pretty pink clouds of beautifulness that had surrounded my previous python experiences: magic names (I felt almost as sad as when I discovered the strange pink worms that eat you in nethack, not to mention the mind flayers - I really hate them). I guess all programming languages have magic names to some...
1
1680
by: robert2821 | last post by:
Hi, I'm new; greetings all! I'm wondering if the following program should work. I think it should print 'Hello, World', but instead it produces a TypeError. Is this a bug in decorators, a feature of them, or a mistake or misunderstanding on my part? TIA, Bob
0
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9484
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9957
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7505
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5386
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5518
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4055
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.