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?
For this simplified example, I think that what you have works pretty well (aside from being a bit hacky). While the
i=ipart can be ugly and tricky, it is a relatively well known way to make closures. Add a comment if you’re afraid someone won’t get it.However, if you’re doing something that’s more complex, I’d definitely agree with S. Lott above.
One other possible approach:
Personally, I feel that this makes the whole thing a lot easier to understand as you’re separating out each iteration of the loop into its own function.