News for hackers. Stuff that matters.
Re:Python idioms by skimbrel on Sunday June 12, 2011 @08:11PM (#2647703)
Use function factories to create utility functions. Often, especially if you're using map and filter a lot, you need utility functions that convert other functions or methods to taking a single parameter. In particular, you often want to bind some data to the function once, and then apply it repeatedly to different objects. In the above example, we needed a function that multiplied a particular field of an object by 3, but what we really want is a factory that's able to return for any field name and amount a multiplier function in that family:

  def multiply_by_field(fieldname, multiplier):
    """Returns function that multiplies field "fieldname" by multiplier."""
    def multiplier(x):
        return getattr(x, fieldname) * multiplier
    return multiplier

  triple = multiply_by_field('Count', 3)
  quadruple = multiply_by_field('Count', 4)
  halve_sum = multiply_by_field('Sum', 0.5)
Other languages (most prominently Haskell, though you can convince most Lisps to do it through the clever use of macros) have built-in support for doing this with whatever function you want, and it's called partial function application. It's a rather useful technique and it saddens me that it's not supported as such in more languages claiming to support functional programming.
Re:Python idioms by Lycanthrope on Sunday June 12, 2011 @08:53PM (#2647773)
There is functools.partial:

  from functools import partial
  def add(x,y): return x+y
  add3 = partial(add, 3)
  add3(2) # returns 5
Re:Python idioms by skimbrel on Monday June 13, 2011 @12:21AM (#2648120)
Ah! I didn't know about that. It'd be nice to have the syntactic sugar à la Haskell, but oh well. Close enough.
Re:Python idioms by herdrick on Monday June 13, 2011 @05:40PM (#2650835)
You don't need a macro to do that in a lisp. Typically you just use a built in 'partial' function, which just makes a closure that will call the original function. (It's simple, so you can just make your own if you're using a lisp without it built in.)