Hacker News new | ask | show | jobs
Managing State in Python (a.k.a. Redux?)
1 points by erikvdven 931 days ago
We're familiar with Flux and Redux in React, for the ones ever programmed in React, but what if we're building an application in Python, for example, with FastAPI, and we don't want to use a database? How do we manage state in such applications? And by that, I certainly don't mean simply storing a variable in a cookie or setting a global variable (which is a poor choice), but state with objects that are dependend on each other.

In React, when a component changes, you can have other components that are able to subscribe to the same 'store,' which then, depending on that state, also gets modified (that's what I remember, if that's false, please show me in the commments). I want to achieve the same principle in Python. I have various objects that are (partially) dependent on each other. For example, I have a RecipeBook class and a Fridge class, to put it simply. The RecipeBook class can provide recipes based on the state of the Fridge class (aka what ingredients do we have at home)

I can add methods and pass the relevant object (such as an instance of Fridge) in each method of the RecipeBook instance, which returns the appropriate recipes. But if I want to have all objects in one State dataclass, it doesn't make sense to get the Fridge from the State and RecipeBook and when calling a method, passing the right object as attribute. Especially when you are maintaining a State with 20 different classes. Moreover, you typically have only one Fridge instance in your project, which is mutable. So, it even might make sense to have a private attribute in RecipeBook with a reference to the Fridge object.

This seems like a good idea, but those instances need to be created at some point, and sometimes a Fridge can be destroyed and a new one created, requiring all the right pointers to be reset.

In short, it's challenging. But it seems to me that I'm not the first one struggling with this. So, my question is, are there any good resources, best practices, or packages available for this? I was thinking about Pydantic, but whether to use pointers or not, or whether to keep passing the objects to each other, remains a question to be answered.

What do you think?

Another solution might even be having an elevated State class, which holds attributes with objects to the RecipeBook and Fridge, and have the methods which need both of them in that elevated class. But I'm not so sure if that's so nice if there are so many different methods when you have like 10 attributes with all different objects.

1 comments

So I'm not able to delete this message so it seems, but guess I already found a solution to this problem: the observer method, which ironically seems to be also implemented by Redux itself.