Python – Stateful vs Stateless Applications Explained

pythonstate

I would like to understand the difference between stateful and stateless applications.

  • What would be a non web app example of a python application which is
    stateless vs stateful?
  • Would a script which scrapes the web and saves the results to disk be
    considered stateful and one which saves the results to a database
    stateless?
  • What about dependencies? Is a script which needs other python
    libraries installed (dependencies) be considered stateful?

Most of what I researched (including this site) was regarding web apps and sessions, I am hoping to get a much broader understanding of this concept.

Best Answer

Technically, computers always have state, even if it is just program state.

So, in order to determine stateful/stateless as we commonly talk about, you have to have some notion of an interaction, request, or even a usage session, and the idea is that the behavior of a second interaction, request, or session does in no way depend on an earlier interaction, request, or session; then it is stateless.

What would be a non web app example of a python application which is stateless vs stateful?

Let's define that an interaction with a calculator is opening the app, calculating, then closing the app. And if such an app doesn't remember anything from one interaction to the next, then it is stateless.

A simpler example would be a REPL calculator that has no memory. Every command line you enter produces a result, but it doesn't remember anything from one command to the next. Thus, each command is independent, and we can consider a run of commands as stateless.

Would a script which scrapes the web and saves the results to disk be considered stateful and one which saves the results to a database stateless?

I would say that you have to look at the behavior of the script as a program as follows: does the script do something different each time it is run, based on the last run? If so, it is stateful, if not it is stateless. In other words, if the script looks at its last run and decides where to start based on that, then it is stateful from run to run. If, however, it starts from scratch and powers thru a fixed set of urls each time, then it is stateless from run to run.

What about dependencies? Is a script which needs other python libraries installed (dependencies) be considered stateful?

Dependency on other pieces of code can make a stateless program stateful. However, libraries are often written as a collection of functions that give you back their state to hold in objects, so you have some control over how stateful they behave by throwing away or holding onto those objects.

Related Topic