[Python-Dev] Function Operators

Reid Kleckner reid.kleckner at gmail.com
Sun Jul 18 17:52:07 CEST 2010


Usual disclaimer: python-dev is for the development *of* python, not
*with*.  See python-list, etc.

That said, def declares new functions or methods, so you can't put
arbitrary expressions in there like type(f).__mul__ .

You can usually assign to things like that though, but in this case
you run into trouble, as shown below:

>>> def func(): pass
...
>>> type(func)
<class 'function'>
>>> def compose(f, g):
...     return lambda x: f(g(x))
...
>>> type(func).__mul__ = compose
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'function'

As the interpreter says, it doesn't like people mucking with operator
slots on built in types.

Finally, if you like coding in that very functional style, I'd
recommend Haskell or other ML derived languages.  Python doesn't
support that programming style very well by choice.

Reid

On Sun, Jul 18, 2010 at 8:34 AM, Christopher Olah
<christopherolah.co at gmail.com> wrote:
> Dear python-dev,
>
> In mathematical notation, f*g = z->f(g(z)) and f^n = f*f*f... (n
> times). I often run into situations in python where such operators
> could result in cleaner code. Eventually, I decided to implement it
> myself and see how it worked in practice.
>
> However, my intuitive implementation [1] doesn't seem to work. In
> particular, despite what it says in function's documentation, function
> does not seem to be in __builtin__. Furthermore, when I try to
> implement this through type(f) (where f is a function) I get invalid
> syntax errors.
>
> I hope I haven't made some trivial error; I'm rather inexperienced as
> a pythonist.
>
> Christopher Olah
>
>
> [1] Sketch:
>
> def __builtin__.function.__mul__(self, f):
>    return lambda x: self(f(x))
>
> def __builtin__.function.__pow__(self, n):
>    return lambda x: reduce(lambda a,b: [f for i in range(n)]+[x])
> _______________________________________________
> Python-Dev mailing list
> Python-Dev at python.org
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: http://mail.python.org/mailman/options/python-dev/reid.kleckner%40gmail.com
>


More information about the Python-Dev mailing list