I'm trying to dynamically create a bunch of class properties, but each dynamic fget accessor needs a unique local variable.
Here is a simplified example:
class Test(object):
def __metaclass__(name, bases, dict):
for i in range(5):
def fget(self, i=i):
return i
dict['f%d' % i] = property(fget)
return type(name, bases, dict)
>>> t = Test()
>>> print t.f0, t.f1, t.f2, t.f4
0, 1, 2, 3, 4
In order to have each correct 'i' value available to each fget function, I have to pass it as a keyword argument when creating the function. Otherwise, all functions would see the same instance of i (the last one generated from the range operation).
This seems like a bad hack to me, is there a better way to do it?