-1

When attempting to dynamically add functions to an object, I'm observing a weird situation.

During the process, it seems to be working fine, as every function returns the expected value.

But when calling each one of these functions again at the end of the process, they all seem to "point" to the last one added to the object.

Here is my code:

class Object:
    pass

obj = Object()

print('during initialization:')
for n in range(3):
    funcName = f'func{n}'
    setattr(obj, funcName, lambda : n)
    print(f'- {funcName} returns {getattr(obj, funcName)()}')

print('after initialization:')
print(f'- func0 returns {obj.func0()}')
print(f'- func1 returns {obj.func1()}')
print(f'- func2 returns {obj.func2()}')

And here is its printout:

during initialization:
- func0 returns 0
- func1 returns 1
- func2 returns 2
after initialization:
- func0 returns 2
- func1 returns 2
- func2 returns 2

Can anyone please help explaining this?

I guess that several similar questions have already been asked here a bunch of times, but I'm not really sure how to search for them.

bbbbbbbbb
  • 107
  • 2
  • 1
    The term you're looking for is "Python lambda closure". Your issue can be fixed via `lambda n=n: n` – Paul M. Aug 23 '23 at 18:57
  • https://stackoverflow.com/questions/3431676/creating-functions-or-lambdas-in-a-loop-or-comprehension – Thierry Lathuille Aug 23 '23 at 18:58
  • @Brian61354270: Yes it does, but in a very unfortunate manner, quote: `Easily fixed by forcing early binding`... early binding is exactly what I am trying to avoid here. I am interested in adding functions dynamically, without knowing their names ahead of time (i.e., only during runtime). Any chance you'd know how to achieve that, given the problem at hand? – bbbbbbbbb Aug 23 '23 at 19:01
  • @PaulM.: Superb!!! Thank you very much! – bbbbbbbbb Aug 23 '23 at 19:03

0 Answers0