13

So I was playing around with currying functions in Python and one of the things that I noticed was that functools.partial returns a partial object rather than an actual function. One of the things that annoyed me about this was that if I did something along the lines of:

five = partial(len, 'hello')
five('something')

then we get

TypeError: len() takes exactly 1 argument (2 given)

but what I want to happen is

TypeError: five() takes no arguments (1 given)

Is there a clean way to make it work like this? I wrote a workaround, but it's too hacky for my taste (doesn't work yet for functions with varargs):

def mypartial(f, *args):
  argcount = f.func_code.co_argcount - len(args)
  params = ''.join('a' + str(i) + ',' for i in xrange(argcount))
  code = '''
def func(f, args):
  def %s(%s):
    return f(*(args+(%s)))
  return %s
  ''' % (f.func_name, params, params, f.func_name)

  exec code in locals()
  return func(f, args)

Edit: I think it might be helpful if I added more context. I'm writing a decorator that will automatically curry a function like so:

@curry
def add(a, b, c):
  return a + b + c

f = add(1, 2) # f is a function
assert f(5) == 8

I want to hide the fact that f was created from a partial (maybe a bad idea :P). The message that the TypeError message above gives is one example of where whether something is a partial can be revealed. I want to change that.

This needs to be generalizable so EnricoGiampieri's and mgilson's suggestions only work in that specific case.

lazytype
  • 927
  • 6
  • 11
  • 1
    Is there anything wrong with `lambda : len('hello')`? I'm always a little hazy on what `functools.partial` does above and beyond `lambda` ... – mgilson Nov 20 '12 at 23:04
  • @mgilson: Well, it makes the error messages even worse. Instead of `TypeError: len() takes exactly 1 argument (2 given)` you'll get `TypeError: () takes 0 positional arguments but 1 was given`. – abarnert Nov 20 '12 at 23:09
  • @mgilson: what happens if you have two functions, which take a different number of params each. A `lambda` needs to know exactly how many args it's going to take beforehand… unless of course, you wrap the args in a tuple and unpack them in the `lambda` – inspectorG4dget Nov 20 '12 at 23:09
  • @mgilson: See if my edit above answers that – lazytype Nov 20 '12 at 23:11
  • @abarnert -- Isn't that almost what OP said was desired? "But what I want to happen is: `TypeError: five() takes no arguments (1 given)`"? – mgilson Nov 20 '12 at 23:12
  • There are already multiple `curry` implementations on ActiveState and PyPI (although some of them are actually `partial` implementations mislabeled); are you sure you need to write a new one from scratch? – abarnert Nov 20 '12 at 23:12
  • @mgilson: yes, that is closer to what I desire, for the specific case – lazytype Nov 20 '12 at 23:13
  • @abarnert: I'm unfamiliar with other implementations, but this is mostly just an exercise. – lazytype Nov 20 '12 at 23:14
  • You're never going to get an error message referring to `five` from something that works comparably to `five = partial(len, 'hello')`. `partial` is called with the arguments `len` and `'hello'`, and does something to come up with an object, which it returns. **Only after that** is it bound to the name `five`, and it could easily be passed around and rebound to other names, even many names at the same time. Expecting the partial object to know about the name `five` is the same as expecting the number `1` to know about the name `a` after executing `a = 1`. Neither makes much sense. – Ben Nov 20 '12 at 23:18
  • Well, it's probably worth reading those other implementations to see what they do—you'll learn a lot. Meanwhile, I assume you want the name of what comes out of `@curry\ndef add…` to be `add`. So, it's not that you want to assign a new name to the function, but that you want to keep the original name, instead of one of the intermediate ones, right? In that case, see `@wraps`. – abarnert Nov 20 '12 at 23:18
  • @abarnert: Okay, I'll check out those other implementations. The name doesn't matter too much to me, just the expected number of arguments. It doesn't look like you can directly modify the number of arguments that a function takes. – lazytype Nov 20 '12 at 23:24
  • @Ben: I'm not too worried about the name; that can be arbitrary. It's the expected number of arguments that I want to be right – lazytype Nov 20 '12 at 23:26
  • There are ways to create a function that takes a static number of args that isn't known until runtime, but really, that's not what you want anyway, because `curry(foo)` never takes a static number of args (except when it takes 0). You're going to have to do the `*args` thing. See my answer for more details. – abarnert Nov 20 '12 at 23:31

2 Answers2

6

You definitely don't want to do this with exec.

You can find recipes for partial in pure Python, such as this one—many of them are mislabeled as curry recipes, so look for that as well. At any rate, these will show you the proper way to do it without exec, and you can just pick one and modify it to do what you want.

Or you could just wrap partial

However, whatever you do, there's no way the wrapper can know that it's defining a function named "five"; that's just the name of the variable you store the function in. So if you want a custom name, you'll have to pass it in to the function:

five = my_partial('five', len, 'hello')

At that point, you have to wonder why this is any better than just defining a new function.

However, I don't think this is what you actually want anyway. Your ultimate goal is to define a @curry decorator that creates a curried version of the decorated function, with the same name (and docstring, arg list, etc.) as the decorated function. The whole idea of replacing the name of the intermediate partial is a red herring; use functools.wraps properly inside your curry function, and it won't matter how you define the curried function, it'll preserve the name of the original.

In some cases, functools.wraps doesn't work. And in fact, this may be one of those times—you need to modify the arg list, for example, so curry(len) can take either 0 or 1 parameter instead of requiring 1 parameter, right? See update_wrapper, and the (very simple) source code for wraps and update_wrapper to see how the basics work, and build from there.

Expanding on the previous: To curry a function, you pretty much have to return something that takes (*args) or (*args, **kw) and parse the args explicitly, and possibly raise TypeError and other appropriate exceptions explicitly. Why? Well, if foo takes 3 params, curry(foo) takes 0, 1, 2, or 3 params, and if given 0-2 params it returns a function that takes 0 through n-1 params.

The reason you might want **kw is that it allows callers to specify params by name—although then it gets much more complicated to check when you're done accumulating arguments, and arguably this is an odd thing to do with currying—it may be better to first bind the named params with partial, then curry the result and pass in all remaining params in curried style…

If foo has default-value or keyword args, it gets even more complicated, but even without those problems, you already need to deal with this problem.

For example, let's say you implement curry as a class that holds the function and all already-curried parameters as instance members. Then you'll have something like this:

def __call__(self, *args):
    if len(args) + len(self.curried_args) > self.fn.func_code.co_argcount:
        raise TypeError('%s() takes exactly %d arguments (%d given)' %
                        (self.fn.func_name, self.fn.func_code.co_argcount,
                         len(args) + len(self.curried_args)))
    self.curried_args += args
    if len(self.curried_args) == self.fn.func_code.co_argcount:
        return self.fn(*self.curried_args)
    else:
        return self

This is horribly oversimplified, but it shows how to handle the basics.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • The reason I'm using exec is because I need to define a function that takes exactly X arguments, but I won't know what X is until runtime. (Okay, that's not exactly true. I could just pass the number of arguments as a parameter to my curry decorator (see edit), but I want to avoid that) – lazytype Nov 20 '12 at 23:18
  • @epsilon: You can find that through inspection, or… really, look at the code in the existing `functools` stuff (http://hg.python.org/cpython/file/2.7/Lib/functools.py for 2.7), and some of those PyPI modules and AS recipes for some ideas of what's possible, and what's a reasonable way to do what's possible. – abarnert Nov 20 '12 at 23:19
  • I'm able to find the value just fine via func.func_code.co_argcount, but it's creating the function with that number of parameters which is problematic. I'll check out some of those recipes, thanks. – lazytype Nov 20 '12 at 23:22
  • @epsilon: You pretty much have to define a function that just takes `(*args, **kw)`, because, even if `foo` has a fixed argument count, `curry(foo)` can take anywhere from 0 to `foo.func_code.co_argcount` args, and `curry(foo)(x)` can take anywhere from 0 to that-1, and so on. – abarnert Nov 20 '12 at 23:27
  • that's a pretty good point, though it might be reasonable to still do something if there are too many arguments given. – lazytype Nov 20 '12 at 23:30
  • @epsilon: Yes, the reasonable thing to do is something like this: `if len(args) + len(self.curried_args) > self.fn.func_code.co_argcount: raise TypeError('blah blah')`. – abarnert Nov 20 '12 at 23:32
0

My guess is that the partial function just delay the execution of the function, do not create a whole new function out of it.

My guess is that is just easier to define directly a new function in place:

def five(): return len('hello')

This is a very simple line, won't clutter your code and is quite clear, so i wouldn't bother writing a function to replace it, especially if you don't need this situation in a large number of cases

EnricoGiampieri
  • 5,947
  • 1
  • 27
  • 26
  • Well, I'm not an expert on functional programming, but I think that the idea behind the curry operation is to maintain the identity of the original function, so it is a little odd to hide it...but I will see what I can came up with :) – EnricoGiampieri Nov 20 '12 at 23:18
  • On a second thought, what you ask cannot be obtained with a nice sintax, as you first create the curryied function and then assign it to a name. You can get around that, but will be a hack...my suggestion is to stick to the definition of a new function, sorry – EnricoGiampieri Nov 20 '12 at 23:26