Skip to content

What is the best/recommended way to create instance variables? #1182

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
rklasen opened this issue Sep 8, 2023 · 2 comments
Closed

What is the best/recommended way to create instance variables? #1182

rklasen opened this issue Sep 8, 2023 · 2 comments

Comments

@rklasen
Copy link

rklasen commented Sep 8, 2023

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

@hynek
Copy link
Member

hynek commented Sep 8, 2023

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=[]):

@rklasen
Copy link
Author

rklasen commented Sep 8, 2023

Yes, that was precisely what was happening, all SimRecipe instances shared the same SimulationTasks list.

Thanks for the quick help!

@rklasen rklasen closed this as completed Sep 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants