parameterized functions: a question of style

Blair Hall b.hall at
Sun Aug 11 22:46:16 EDT 2002

I would be interested in comments / suggestions regarding the following
attempt  to generate a family of functions.

Suppose (just for arguments sake) I need various functions of the form y
= x**n, where n is a
parameter, ie I want n to be part of the function definition, not an
argument to it!

I am tempted to write

def gen_fn(n):
    def _fn(x):
        return x**n

    return _fn

I could then obtain different functions like

squared = gen_fn(2)
cubed = gen_fn(3)

>>> squared(4)
>>> cubed(3)

The only alternative I can think of to this would be inheritance, ie

class base(object):
    def raise(self,x)
        return x ** self.n

class two(base):
    def __init__(self):
        self.n = 2

class three(base):
    def __init__(self):
        self.n = 3

This solution leaves me with a class, not a function (which is what I
intended to have),
so there would be a further step needed to export the class methods as

Any suggestions, gotchas?
(I realize that the first way uses nested scopes, but that's ok from

More information about the Python-list mailing list