fn.py icon indicating copy to clipboard operation
fn.py copied to clipboard

@composable decorator

Open kachayev opened this issue 11 years ago • 3 comments

Special @composable decorator to bring new functionality to function:

  • easy way to compose functions (using one of standard operators)
  • overload apply operator

kachayev avatar Mar 27 '13 09:03 kachayev

This seems interesting, are you still thinking about it?

berrytj avatar Aug 17 '14 20:08 berrytj

@berrytj Yeah, I still think about it. I just don't want to make obvious mistake: to write decorator which will require special decorators order in each case. Which means that I want @composable decorator to be composable itself.

kachayev avatar Aug 18 '14 08:08 kachayev

(Stating the obvious for a moment.) composable must return a class for operator overrides to work. So any decorator that returns only functions will fail if called after composable, e.g.:

@memoize
@composable
def double(n):
    return n*2

(double * sum)([1, 2])  # => TypeError

I can only think of two ways around this, neither ideal. The first is to modify your decorators inline:

def classdecorator(decorator):
  def inner(f):
    if isinstance(f, types.FunctionType):
      return decorator(f)
    else:
      f.__call__ = decorator(f.__call__)
      return f
  return inner


@classdecorator(memoize)
@composable
def double(n):
  return n*2

(double * sum)([1, 2])  # => works

The second is to use libraries whose decorators have already undergone this operation (to support classes masquerading as functions). The toolz folks might allow that functionality addition.

berrytj avatar Aug 20 '14 05:08 berrytj