Python reactive state management library inspired by MobX
Project description
FynX
FynX ("Finks") = Functional Yielding Observable Networks
FynX is a lightweight reactive state management library for Python that makes your data flow effortlessly. Inspired by MobX and similar functional reactive programming frameworks, FynX transforms plain Python objects into reactive observables that update automatically. You define how your data relates—FynX handles the synchronization with zero boilerplate.
Whether you're building interactive Streamlit dashboards or crafting data-driven UIs, this library ensures that all changes propagate smoothly, predictably, and elegantly throughout your application. When one value changes, everything that depends on it updates automatically. No manual wiring, no stale state, no hassle.
Getting Started
Install FynX with a single command:
pip install fynx
Here's what reactive state management looks like in practice.
For example, imagine you're building a shopping cart and want to display the total price. With FynX, the calculation happens automatically whenever the cart contents change:
from fynx import Store, observable
# Define a store for a shopping cart
class CartStore(Store):
item_count = observable(1)
price_per_item = observable(10.0)
def update_ui(total: float):
print(f">>> Cart Total: ${total:.2f}")
# Link item_count and price_per_item to auto-calculate total_price
combined_observables = CartStore.item_count | CartStore.price_per_item
# The >> operator takes any observable and passes the value(s) to the right.
total_price = combined_observables >> (lambda count, price: count * price)
total_price.subscribe(update_ui) # Subscribe and update the UI when it changes
print("=" * 50)
# Now whenever we change the cart state, total_price updates automatically,
# and the UI is updated accordingly.
CartStore.item_count = 2
CartStore.price_per_item = 15
# ==================================================
# >>> Cart Total: $20.00
# >>> Cart Total: $30.00
That's the essence of FynX. Define your relationships once, and the library ensures everything stays synchronized. You never write update code again—just describe what should be true, and FynX makes it so.
Where FynX Shines
FynX excels in scenarios where data flows through transformations and multiple components need to stay in sync. Consider Streamlit applications where widgets depend on shared state, or data pipelines where computed values must recalculate when their inputs change. Analytics dashboards that visualize live data, forms with interdependent validation rules, or any system where state coordination becomes complex—these are FynX's natural habitat.
The library frees you from the tedious work of tracking dependencies and triggering updates. Instead of thinking about when to update state, you focus purely on what relationships should hold. The rest happens automatically.
Be sure to check out the examples.
Understanding Observables
At the heart of FynX lies the observable: a value that changes over time and notifies interested parties when it does. You can create standalone observables or organize them into Stores for related state:
from fynx import observable, Store
counter = observable(0)
# You can set standalone observable values with .set(),
counter.set(1)
class AppState(Store):
username = observable("")
is_logged_in = observable(False)
# Stores allow us to treat them as normal values
AppState.username = "off-by-some"
Observables work like normal Python values—you read and write them naturally—but they carry reactive superpowers beneath the surface.
Transforming Data
The >> operator lets you transform observables declaratively. Each transformation creates a new derived observable that automatically recalculates when its source changes:
doubled = counter >> (lambda x: x * 2)
result = (counter
>> (lambda x: x * 2)
>> (lambda x: x + 10)
>> (lambda x: f"Result: {x}"))
If syntactic sugar isn't quite your thing, you can use computed instead:
from fynx import computed
# Simple transformation
doubled = computed(lambda x: x * 2, counter)
# Chained transformations (step-by-step)
step1 = computed(lambda x: x * 2, counter)
step2 = computed(lambda x: x + 10, step1)
result = computed(lambda x: f"Result: {x}", step2)
No matter how you write them, these transformations compose naturally. You can chain them indefinitely, and FynX ensures the data flows correctly through each stage.
Combining Multiple Streams
When you need to work with multiple observables together, the | operator combines them into reactive tuples. Change any component, and the combined observable updates:
class User(Store):
first_name = observable("John")
last_name = observable("Doe")
full_name_parts = User.first_name | User.last_name
full_name = full_name_parts >> (lambda first, last: f"{first} {last}")
Now whenever either the first or last name changes, the full name recalculates automatically. This pattern scales elegantly to any number of observables.
Filtering with Conditions
The & operator filters observables so they only emit values when conditions are met. Use ~ to negate conditions. This becomes powerful when building reactive systems with complex business logic:
uploaded_file = observable(None)
is_processing = observable(False)
is_valid = uploaded_file >> (lambda f: f is not None)
preview_ready = uploaded_file & is_valid & (~is_processing)
The preview_ready observable only has a value when a file exists, it's valid, and processing isn't active. All three conditions must align before anything downstream executes.
Reacting to Changes
FynX offers multiple ways to react to observable changes, letting you choose the style that fits each situation. Decorators provide clean syntax for dedicated reaction functions:
@reactive(preview_ready)
def show_preview(file):
print(f"Showing: {file}")
Subscriptions work well for inline reactions:
full_name.subscribe(lambda name: print(f"Name: {name}"))
Context managers create scoped reactions that clean up automatically:
with full_name_parts as react:
react(lambda first, last: print(f"Changed to: {first} {last}"))
For reactions that should only trigger when specific conditions become true, the watch decorator monitors multiple conditions simultaneously:
@watch(lambda: User.age.value >= 18, lambda: User.email.value.endswith('.com'))
def process_eligible_user():
print("Eligible user detected!")
The Reactive Operators
FynX provides four core operators that compose into sophisticated reactive systems.
- The
>>operator transforms values through functions. - The
|operator combines multiple observables into tuples. - The
&operator filters based on boolean conditions. - The
~operator negates those conditions.
Together, these operators form a complete algebra for reactive data flow.
Consider total_price >> (lambda t: f"${t:.2f}") for transformations, (first | last) >> (lambda f, l: f"{f} {l}") for combinations, file & is_valid & (~is_processing) for conditional filtering, and ~(is_processing) for negation. Each operation produces a new observable that you can transform, combine, or filter further.
A Complete Example
Here's how these pieces fit together in a practical file upload system. Notice how complex reactive logic emerges naturally from simple compositions:
from fynx import Store, observable, reactive
class FileUpload(Store):
uploaded_file = observable(None)
is_processing = observable(False)
progress = observable(0)
is_valid = FileUpload.uploaded_file >> (lambda f: f is not None)
is_complete = FileUpload.progress >> (lambda p: p >= 100)
ready_for_preview = FileUpload.uploaded_file & is_valid & (~FileUpload.is_processing)
@reactive(ready_for_preview)
def show_file_preview(file):
print(f"Preview: {file}")
FileUpload.uploaded_file = "document.pdf" # Preview: document.pdf
FileUpload.is_processing = True
FileUpload.uploaded_file = "image.jpg" # No preview (processing active)
FileUpload.is_processing = False # Preview: image.jpg
The preview function triggers automatically, but only when all conditions align. You never manually check whether to show the preview—the reactive graph handles that coordination.
Going Deeper
FynX supports more sophisticated patterns for complex applications. Store-level reactions give you snapshots of all observables whenever anything changes, perfect for logging or persistence:
@reactive(UserProfile)
def on_any_change(snapshot):
print(f"Profile updated: {snapshot.first_name} {snapshot.last_name}")
Stores also provide serialization for state persistence. Save your entire reactive state to a dictionary and restore it later:
state_dict = UserProfile.to_dict()
UserProfile.load_state(state_dict)
Examples
Explore the examples/ directory for demonstrations of FynX's capabilities:
| File | Description |
|---|---|
basics.py |
Core FynX concepts: observables, subscriptions, computed properties, stores, reactive decorators, and conditional logic |
cart_checkout.py |
Shopping cart with reactive total calculation using merged observables and subscriptions |
advanced_user_profile.py |
Complex reactive system demonstrating validation, notifications, state persistence, and sophisticated computed properties |
streamlit/store.py |
Custom StreamlitStore implementation with automatic session state synchronization |
streamlit/todo_app.py |
Complete reactive todo list application with Streamlit UI, showcasing real-time updates and automatic persistence |
streamlit/todo_store.py |
Todo list store with computed properties, filtering, and bulk operations |
The Mathematical Foundation
If you're curious about the theory powering FynX, the core insight is that observables form a functor in the category-theoretic sense. An Observable<T> represents a time-varying value—formally, a continuous function $\mathcal{T} \to T$ where $\mathcal{T}$ denotes the temporal domain. This construction naturally forms an endofunctor $\mathcal{O}: \mathbf{Type} \to \mathbf{Type}$ on the category of Python types.
The >> operator implements functorial mapping, satisfying the functor laws. For any morphism $f: A \to B$, we get a lifted morphism $\mathcal{O}(f): \mathcal{O}(A) \to \mathcal{O}(B)$, ensuring that:
$$ \begin{align*} \mathcal{O}(\mathrm{id}A) &= \mathrm{id}{\mathcal{O}A} \ \mathcal{O}(g \circ f) &= \mathcal{O}g \circ \mathcal{O}f \end{align*} $$
The | operator constructs Cartesian products in the observable category, giving us $\mathcal{O}(A) \times \mathcal{O}(B) \cong \mathcal{O}(A \times B)$. This isomorphism means combining observables is equivalent to observing tuples—a property that ensures composition remains well-behaved.
The & operator forms filtered subobjects through pullbacks. For a predicate $p: A \to \mathbb{B}$ (where $\mathbb{B}$ is the boolean domain), we construct a monomorphism representing the subset where $p$ holds true:
$$ \mathcal{O}(A) \xrightarrow{\mathcal{O}(p)} \mathcal{O}(\mathbb{B}) \xrightarrow{\text{true}} \mathbb{B} $$
This isn't merely academic terminology. These mathematical properties guarantee that reactive graphs compose predictably through universal constructions. Functoriality ensures transformations preserve structure: if $f$ and $g$ compose in the base category, their lifted versions $\mathcal{O}(f)$ and $\mathcal{O}(g)$ compose identically in the observable category. The pullback construction for filtering ensures that combining filters behaves associatively and commutatively—no matter how you nest your conditions with &, the semantics remain consistent.
Category theory provides formal proof that FynX's behavior is correct and composable. The functor laws guarantee that chaining transformations never produces unexpected behavior. The product structure ensures that combining observables remains symmetric and associative. These aren't implementation details—they're mathematical guarantees that follow from the categorical structure itself.
But what are the practical benefits of this? Ultimately, it's that changes flow through your reactive graph transparently because the mathematics proves they must. FynX handles all dependency tracking and propagation automatically, and the categorical foundation ensures there are no edge cases or surprising interactions. You describe what you want declaratively, and the underlying mathematics—specifically the universal properties of functors, products, and pullbacks—ensures it behaves correctly in all circumstances.
Design Philosophy
FynX embodies a simple principle: mathematical rigor shouldn't compromise usability. The library builds on category theory but exposes that power through Pythonic interfaces. Observables behave like normal values—you read and write them naturally—while reactivity happens behind the scenes. Method chaining flows naturally: observable(42).subscribe(print) reads like plain English.
Composability runs through every aspect of the design. Transform with >>, combine with |, filter with &. Each operation produces new observables that you can transform further. Complex reactive systems emerge from simple, reusable pieces. This compositional approach mirrors how mathematicians think about functions and morphisms, but you don't need to know category theory to benefit from its guarantees.
FynX offers multiple APIs because different situations call for different tools. Use decorators for convenience, direct calls for control, or context managers for scoped reactions. The library adapts to your style rather than forcing one approach.
Framework agnosticism matters. FynX works with Streamlit, FastAPI, Flask, or any Python framework. The core library has zero dependencies and integrates cleanly with existing tools. Whether you're building web applications, data pipelines, or desktop software, FynX fits naturally into your stack.
API Reference
Core Functions
observable(initial_value) creates a reactive value that notifies subscribers when changed. This forms the foundation of reactive state in FynX.
reactive(observable) provides a decorator that reacts to observable changes, executing the decorated function whenever the observable emits a new value.
watch(*conditions, callback) monitors specific conditions and triggers callbacks when those conditions become true, enabling reactive logic based on boolean expressions.
Classes
Store serves as a base class for organizing related observables with built-in serialization support. Stores provide structure for complex state management and enable persistence patterns.
Contributing
We welcome contributions to FynX. The project uses Poetry for dependency management and pytest for testing. To get started:
poetry install --with dev --with test
poetry run pre-commit install
poetry run pytest
The pre-commit hooks run automatically on each commit, checking code formatting and style. You can also run them manually across all files with poetry run pre-commit run --all-files.
To verify your changes pass all tests and coverage requirements, run poetry run pytest --cov=fynx. The linting script at ./scripts/lint.sh checks for issues, and ./scripts/lint.sh --fix automatically fixes formatting and import problems.
When contributing, fork the repository and create a feature branch with a descriptive name like feature/amazing-feature. Make your changes, add comprehensive tests, and ensure the test suite passes. Submit a pull request with a clear description of what you've changed and why.
Visualizing Current Test Coverage
FynX maintains comprehensive test coverage tracked through Codecov. Here are visual representations of our current coverage:
| Sunburst Diagram | Grid Diagram | Icicle Diagram |
|---|---|---|
The inner-most circle represents the entire project, with folders and files radiating outward. Size and color represent statement count and coverage percentage. |
Each block represents a file. Size and color indicate statement count and coverage percentage. |
The top section represents the entire project, with folders and files below. Size and color represent statement count and coverage percentage. |
License
FynX is licensed under the MIT License. See the LICENSE file for complete details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fynx-0.0.4.tar.gz.
File metadata
- Download URL: fynx-0.0.4.tar.gz
- Upload date:
- Size: 32.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.0 CPython/3.13.7 Linux/6.15.11-2-MANJARO
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
219b1ab8866f812c2c09623d599be43cff9158a9daf96d2d92fafc4b0fae8b1b
|
|
| MD5 |
d3d60e95f9476b36c5b47556703b512b
|
|
| BLAKE2b-256 |
82b01031f3fd66b971c86148625c55505eab98bcf892937298cb220c24a0b5cc
|
File details
Details for the file fynx-0.0.4-py3-none-any.whl.
File metadata
- Download URL: fynx-0.0.4-py3-none-any.whl
- Upload date:
- Size: 33.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.0 CPython/3.13.7 Linux/6.15.11-2-MANJARO
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d13fc240f98a158e8b45833c82a708e7a8e6344cd07ded8dfacd4170e217596e
|
|
| MD5 |
1cc781de3e9f4336a33115c338ba816b
|
|
| BLAKE2b-256 |
bfbdfe500f07862c0f0370f1a198e379955d97354a6a5de3e760046ac6254c59
|