Overloading operators for currying, a PEP309 suggestion

Stephen Horne intentionally at blank.co.uk
Tue Mar 11 07:41:27 EST 2003


On Tue, 11 Mar 2003 03:50:30 GMT, "Lenard Lindstrom"
<PEP308reply at telus.net> wrote:

>In PEP 309 a new operator, '@', was tentatively proposed for currying. But
>given that Python allows operator overloading, why not use some existing
>operators for currying 'function' objects? The 'function' class has few
>operations defined for it, so there remain many to choose from. Here are my
>suggestions:

You may be onto something, but I'm not keen on your '|' version in
particular.

I would prefer defining the __len__, __getitem__, __setitem__ and
__delitem__ methods to allow direct manipulation (and creation and
deletion) of the closure. Though probably the function object should
be immutable.

How about...

  <function-obj> [ <int> | <slice> ] -> <closure-item-ref>
  <function-obj> . <keyword>         -> <closure-item-ref>
    Each returns a new type - a reference to the function with the
    closure so far, plus an indication of the part of the closure
    being referenced.

  <closure-item-ref> ( args )
    Call the function with the closure restricted to only the
    referenced part.

  <closure-item-ref> | <closure-item-ref>
    Create a new function-and-closure, merging the items from both
    (with priority given to the selected fields) and merging the
    selection masks.

  <closure-item-ref> << <value>
    Return a new function/closure with the selected fields from the
    old one added or modified.

That would mean, for a function...

  def fn (a, b, c, d) :
    pass

...you could write...

  fn2 = fn [0] << "x"       #  Curry first parameter
  fn2 = fn [-1] << "x"      #  Curry last parameter

  fn2 = fn.b << "x"         #  Curry keyword parameter

  fn2 = fn [1:2] << (1, 2)  #  Curry a slice

  fn2 = fn [0] | fn [3]     #  Unselect (effectively uncurry) b and c

  fn2.a.value ()            #  Get value currently assigned to a


This is not properly thought through, though - and the '<<' probably
makes no sense to a lot of people.

One advantage - it should be possible to write this as a library
without any language changes. I think.





More information about the Python-list mailing list