0

I'm trying to create properties at runtime for a class, and i'm currently using this piece of code:

class Obj:
  pass

attrs = ["a", "b", "c"]

for attr in attrs:
  attr_print = lambda self: print(attr)
  setattr(Obj, attr, property(attr_print))

o = Obj()
o.a

But whatever attribute i'm trying to print, it always prints the last in attrs.

It feels like python is changing my previous lambdas at each loop.

Is there a way to prevent this happening ?

Julien
  • 87
  • 9

1 Answers1

1

Yes, just use another lambda...

for attr in attrs:
    createProp = lambda a: (lambda self: print(a))
    attr_print = createProp(attr)
    setattr(Obj, attr, property(attr_print))

This way, we create a new variable a in each loop (this a is a parameter/local variable to the function createProp), and the attr_prints then each refer to their own private as.

Tobias
  • 1,321
  • 6
  • 11