Symbols as parameters?

Steven D'Aprano steve at
Fri Jan 29 02:30:05 CET 2010

On Thu, 28 Jan 2010 17:01:38 +0100, Roald de Vries wrote:

> Question out of general interest in the language: If I would want to
> generate such functions in a for-loop, what would I have to do? This
> doesn't work:
>     class Move(object):
>        def __call__(self, direction):
>            return direction
>     move = Move()
>     for f in ['up', 'down', 'right', 'left']:
>         move.__dict__[f] = lambda: move(f)
> ... because now 'move.up()' returns 'left' because thats the current
> value of f. Is there a way to 'expand' f in the loop? Or a reason that
> you never should use this?

Possibly the simplest way is to use Python's handling of default values 
to get the result you want:

for f in ['up', 'down', 'right', 'left']:
    move.__dict__[f] = lambda f=f: move(f)

BTW, there's no need to explicitly reference move.__dict__:

for f in ['up', 'down', 'right', 'left']:
    setattr(move, f, lambda f=f: move(f))


More information about the Python-list mailing list