Symbols as parameters?

Roald de Vries rdv at
Fri Jan 29 09:08:56 CET 2010

On Jan 29, 2010, at 2:30 AM, Steven D'Aprano wrote:
> 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)

This still leaves open the possibility of move.up('down') resulting in  
move('down'), but for the rest I like it.

> 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))

I expected something like that. Thanks.


More information about the Python-list mailing list