Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function closure vs. callable class

In many cases, there are two implementation choices: a closure and a callable class. For example,

class F:
  def __init__(self, op):
    self.op = op
  def __call__(self, arg1, arg2):
    if (self.op == 'mult'):
      return arg1 * arg2
    if (self.op == 'add'):
      return arg1 + arg2
    raise InvalidOp(op)

f = F('add')

or

def F(op):
  if op == 'or':
    def f_(arg1, arg2):
      return arg1 | arg2
    return f_
  if op == 'and':
    def g_(arg1, arg2):
      return arg1 & arg2
    return g_
  raise InvalidOp(op)

f = F('add')

What factors should one consider in making the choice, in either direction?

I can think of two:

  • It seems a closure would always have better performance (can't think of a counterexample).

  • I think there are cases when a closure cannot do the job (e.g., if its state changes over time).

Am I correct in these? What else could be added?

like image 990
max Avatar asked Jan 23 '12 03:01

max


1 Answers

Closures are faster. Classes are more flexible (i.e. more methods available than just __call__).

like image 126
Raymond Hettinger Avatar answered Nov 16 '22 03:11

Raymond Hettinger