squared functions--most Pythonic way?

Aahz aahz at pythoncraft.com
Sat Jun 29 01:11:55 CEST 2002


In article <ballabio-E54F22.21380327062002 at newssrv.fastweb.it>,
Luigi Ballabio  <ballabio at mac.com> wrote:
>
>      suppose we want to define a function which, given f(x), returns 
>its square. There are a number of ways which come to mind, such as:
>
>object-oriented programming:
>
>    def fsquare:
>        def __init__(self,f):
>            self.f = f
>        def __call__(self,x):
>            return self.f(x)**2
>
>functional programming:
>
>    # with an internal named function
>    def fsquare(f):
>        def f2(x):
>            return f(x)**2
>        return f2

I'm sensing an ill-defined spec here.  To me, your English sentence
implies that what's wanted is

    def fsquare(f, x):
        return f(x)**2

but both of your examples define closures of some sort.

Assuming that your code does what you really want, I don't think either
of these two is "more Pythonic"; it depends on your circumstances and
who your likely code readers are going to be.  I don't have much
functional experience, so the OO mechanism works better for me
(particularly given that it works back to 1.5.2).
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Project Vote Smart: http://www.vote-smart.org/



More information about the Python-list mailing list