Python Forum
Simple way of curryfying callables
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Simple way of curryfying callables
#1
Currying is the process of transforming a function with signature e.g. (X, Y, Z) -> T into a function having signature X -> (Y -> (Z -> T)). For example the following spam() function
def spam(x, y, z):
    ...
is normally called with the syntax spam(7, 4, 3). A curried version would be called with the syntax spam(7)(4)(3).

The code below automates the process of currying the functions. It also provides a decorator to curryfy the functions as soon as they are defined.
__version__ = '2026.01.27'

class Curry:
    def __init__(self, arity, func, args: tuple=()):
        self.arity = arity
        self.func = func
        self.args = args

    def __repr__(self):
        return f'Curry({self.arity!r}, {self.func!r}, {self.args!r})'

    def __call__(self, arg):
        if self.arity == 1:
            return self.func(*self.args, arg)
        return Curry(self.arity - 1, self.func, self.args + (arg,))

curry = Curry(2, Curry)

@curry(3)
def spam(a, b, c):
    return ('result', a, b, c)

print(spam(7)(4)(3)) # prints ('result', 7, 4, 3)
Of course there are many modules devoted to this in the Cheese Shop.
« We can solve any problem by introducing an extra level of indirection »
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020