Symbols as parameters?

S

Steven D'Aprano

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,786
Messages
2,569,626
Members
45,323
Latest member
XOBJamel3

Latest Threads

Top