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

No members online now.

Forum statistics

Threads
474,001
Messages
2,570,254
Members
46,851
Latest member
CliftonCor

Latest Threads

Top