Skip to main content

Appstate

Minimalistic reactive local application state toolkit.

This package provides a way to store application state in a form of single-rooted recursive key-value tree, and means to subscribe to the changes made to the branches of interest.

Introduction

Let's consider a common application which has a "screen" for user to change configuration and another "screen" which allows to perform something useful, depending on the current configuration.

If we organize our application into separate "configuration screen" module and "main screen" module, we would have to ensure the "main screen" reacts accordingly when user changes values on "configuration screen".

Traditional methods to compose the app from the modules together includes direct function calling, "callbacks" pattern, "signal\slot" pattern and some others. The approach provided by this package may be considered as a mix of "signal\slot" pattern and "reactive programming".

To address our app case, we can make configuration screen module write any setting to the state:

from app_state import state

# This should likely happen in 'OK' button click callback, not displayed here.
state.username = 'value'  

And we let the main screen module to subscribe to the setting by decorating a function wich will read changed value from state and update main screen display:

from app_state import state, on

@on('state.username')
def change_user():
    title.text = 'Hello, ' + state.username

Installation

pip install app_state

Usage

from app_state import state

state["some_data"] = 42  # Alternatively: state.some_data = 42

State is a recursive dictionary-like object. For covenience, branches can also be accessed with . as attributes.

Listen for state changes

@on(*patterns) decorator makes the decorated function or method to be called each time when the state subtree changes. Each pattern is a dot-separated string, representing state subtree path.

from app_state import state, on

@on('state.countries')
def countries():
    print(f'countries changed to: {state.countries}')
    
@on('state.countries.Australia.population')
def au_population():
    population = state.get('countries', {}).get('Australia', {}).get('population')
    print(f'Australia population now: {population}')
    
state.countries = {'Australia': {'code': 'AU'}, 'Brazil': {}}
state.countries.Australia.population = 4500000
    

will print:

countries changed to: {'Australia': {'code': 'AU'}, 'Brazil': {}}
Australia population now: None
countries changed to: {'Australia': {'code': 'AU', 'population': 4500000}, 'Brazil': {}}
Australia population now: 4500000

@on() can wrap a method of a class. When state changes, that method will be called for every instance of this class.

from app_state import state, on

class MainWindow:
    @on('state.user')
    def on_user(self):
        self.settext(f'Welcome, {state.user.name}')

mainwindow = MainWindow()

state.user = {'name': 'Alice'}  # mainwindow.on_user() will be called.

Persistence

By default the state is stored in memory. But it is possible to automatically store the state to a file when it is changed. Call state.autopersist('myfile') to enable persistence. This function will load the state from the file, and turn on automatic storage of the state to this file.

If you want to exclude some branches from persistence, then you should store them as attributes, starting with underscore:

# `_temp_peers` will never be stored to a file
state.countries.Australia._temp_peers = [{'ip': '8.8.8.8'}]

API

state.autopersist(filepath, timeout=3, nursery=None)

Enable automatic state persistence, create a shelve with a given filepath. If file already exists, read state from it.

timeout - how many seconds to wait before writing to the file after each state change. This parameter helps to reduce frequent writes to disk, grouping changes together. Only works when state changes happen in a thread with asyncio or trio event loop.

nursery - required if trio is used.

class DictNode

app_state.state and every its subtree is an instance of DictNode. Normally you don't need to use this class explicitly. Instance of DictNode is a dict-like object which emit signal when it is changed, so that functions decorated with on() decorator get called appropriately. When you create a dictionary and assign it to any state branch, it will be implicitly converted to DictNode:

from app_state import state, DictNode
state.countries = {}
assert isinstance(state.countries, DictNode)  # True

as_dict(full=False)

This method returns regular dictionary, converting DictNode and all subnodes.

If full is True, then all attributes, starting with underscore will also be included in the dictionary as keys.

state.config = {'name': 'user1'}
state.config._session_start = '16:35'
print(state.config.as_dict(full=True))
# prints {'name': 'user1', '_session_start': '16:35'}

Metadata

Release files for app_state 0.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for app_state 0.7
File Size Uploaded
app_state-0.7.tar.gz 7.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for app_state 0.7
File Interpreter ABI Platform
app_state-0.7-py3-none-any.whl Python 3 none any Details

Total release size: 15.2 kB

Release files / app_state-0.7.tar.gz

Download URL app_state-0.7.tar.gz
Size 7.4 kB
Tags Source
SHA-256 checksum
How to use checksums
3ac0aae3d922eece9dd1d362b5a3da30b073d9dc3c96df88c8b96e7d98c48a23
BLAKE2b-256 checksum
How to use checksums
eba0c3f121f9dec1e997a43ccafec541bc589f467f2c08d250311e45a630d0ba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via pdm/2.21.0 CPython/3.11.11 Linux/6.12.6-1-default

Release files / app_state-0.7-py3-none-any.whl

Download URL app_state-0.7-py3-none-any.whl
Size 7.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ed157f7805955d6f5647c6f8f7dd44cf85af86073fd275f44396a47a697d1647
BLAKE2b-256 checksum
How to use checksums
a7b4b0c57550a5e92e11ddb6ca61a64ec28b4e35bf76e0a0bc0f29960c6bb046
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via pdm/2.21.0 CPython/3.11.11 Linux/6.12.6-1-default

Release history Release notifications | RSS feed

This release

0.7 This release

2 release files

0.6

2 release files

0.5

2 release files

0.4

2 release files

0.3

2 release files

0.2

2 release files

0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page