What is the best/recommended way to create instance variables?
rklasen opened this issue · 2 comments
Hi, sorry to create an issue for what may be a newbie question, but I've browsed the closed issues and the problem seems to occur often.
I have a dataclass that should hold a list of instances of another class:
@define
class SimRecipe:
SimulationTasks: List[SimulationTask] = []
I didn't realize that SimulationTasks
would be a class variable instead of an instance variable.
In #972 (comment) it's suggested to give an initial value so that the variable becomes an instance variable, but that doesn't seem to work here.
What would be the cleanest way to make it an instance variable?
Best wishes
SimulationTasks is not an instance variable, but I suspect I know what's happening:
You're setting a default of a list ([]
) that is shared between all instance variables.
What you need to do is = attrs.Factory(list)
or = attrs.field(factory=list)
This is the Python mistake that everyone makes and comparable to the classic def f(x=[]):
Yes, that was precisely what was happening, all SimRecipe
instances shared the same SimulationTasks
list.
Thanks for the quick help!