Function question

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Tue Apr 9 13:22:41 EDT 2002


On Sun, 7 Apr 2002 23:55:47 -0500, John <nobody at nobody.com> wrote:
>
>Hi I have a question:
>
>Let's say there is a function with two arguments.
>def add(a,b): return a+b
>
>What I want to do is:
>I want to get 'a' dynamically..
>But once a value is decided, I want a separate function (say, new_add) that
>does
>new_add(b) (equals to) add(a,b)
>
>That is, I want the function definition to be dynamic.
>
>Would that be possible? Any comment would be greatly appreciated.

The easiest way With Python 2.2:

>>> def f1(a):
...    def f2(b):
...       return a+b
...    return f2
... 
>>> f = f1(3)
>>> f(3)
6
>>> f(2)
5
>>> f(-1)
2

With Python 2.1 put this at the beginning of module:

from __future__ import nested_scopes

With earlier Python, use default arguments, like def f2(b, a=a), but this
has risks.

Or, if there are more than a few arguments, you might want to use a callable
object (an instance of a class with a __call__ method).

Huaiyu



More information about the Python-list mailing list