[ANN] Partial.py: convenient notation for partial application/currying

Jeff Epler jepler at unpythonic.net
Thu Jun 26 04:24:26 CEST 2003

Hm, interesting.

> >>> mapcall(_.upper, ["list", "of", "strings"])

So you are forced to use 'mapcall' instead of 'map' for some reason?  It
seems like you could define _ in such a way that this was not necessary
(this may not fit in with your whole module, though---also, performance of
my approach is untested and uncompared with mapcall(_., ...).

class MethodCaller:
	def __init__(self, method_name):
		self.method_name = method_name
	def __call__(self, obj, *args, **kw):
		method = getattr(obj, self.method_name)
		return method(*args, **kw)

class UnderscoreMaker:
	def __init__(self): pass
	def __getattr__(self, m):
		return MethodCaller(m)

_ = UnderscoreMaker()

>>> map(_.upper, "abc")
['A', 'B', 'C']

Here's an api idea (no implementation) for currying:

	def f(x, y, z): print x, y, z
	class C:
		f = f

# _[] gives a curryable, and curryable[] curries.  _ when currying leaves
# the arg open.  If this was integrated in the language, f[_, ...] would
# mean the same thing as _[f][...]
>>> g = _[f][_, _, 'a']
>>> g(1, 2)
1 2 a
# Might as well allow this shorthand
>>> g = _[f, _, 'a']
>>> g(1, 2)
1 a 2
>>> c = C()
# A MethodCaller is also curryable[].  _ means the same thing
>>> g = _.f['a']
>>> g(c, 1)
<__main__.C instance at 0xdeadbeef> a 1

Of course, there are always those who already have a use for _: the
interactive prompt, gettext-style i18n, and god knows what else...  Also,
the triple-use of _ seems a bit dirty.  Another thing that would be cool is
if Python could perform constant propagation when currying, possibly giving
a better/more efficient function instead of a slower one with more

PS What?  You mean you already had this thread twice this year?  Why wasn't
I invited?

More information about the Python-list mailing list