I'm trying to do the following:
class DoSomething:
def something(self, number, name)
self.main_dict = {}
setattr(self,name,['anything'])
self.main_dict[number] = getattr(self,name)
The above passes the attribute (reference by value) to the dictionary. Not the behavior I need.
I want to pass the reference of the dynamic variable to the dictionary, not the attribute. Further on I modify the dynamic variable and I want it to be reflected in the dictionary.
Is it possible do so such thing?
Edit:
Why?
1) To learn how to do such thing and have one more tool in the toolbox. The answers provided refer to using a "reference / container" class and creating an instance for each value needed. Perfect.
2) Because this problem was created by another fixable problem (didn't see at first). Note I further modify the dynamically created variable. To do so, it needs to be dynamically called by (setattr, vars, __dict__, etc
). It was not being modified, it was being assigned a new value which changes the reference, not reflecting back to the dict.
I would like to point to this about assignment/reference: How do I pass a variable by reference?
3) The intent is maintenance. By referencing at the beginning the dict-variable, the programmer would know any changes made to the variable would reflect into the dictionary.
4) I mentioned in the comments about using lambda
. This would only work if the name
is never modified, otherwise lambda would use the last assigned value to name
.