parameterized functions: a question of style

Oren Tirosh oren-py-l at
Mon Aug 12 06:11:43 CEST 2002

On Mon, Aug 12, 2002 at 02:46:16PM +1200, Blair Hall wrote:
> 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

Why not give in to temptation?  If you are concerned about Python versions 
without nested scopes you could use:

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

Personally, I find it more aesthetically pleasing to use an anonymous
lambda function for this:

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

Or gen_fn=lambda n:lambda x:x**n in case you're a total lambda freak :-)


More information about the Python-list mailing list