GitHub

Example: Counter

Signals, a computed value and a bound number input.

  • 26 lines of Python
  • 1 page
  • 0 server functions
  • 453 B page JS (gzip)
localhost:8000 · live, 453 B of page codeOpen ↗

#Source

examples/counter/app.pyweb
from pyweb import App

app = App(title="Counter")


@app.page("/")
def Home():
    count = 0
    step = 1
    doubled = count * 2

    def increment():
        count += step

    def reset():
        count = 0

    <main>
        <h1>Counter</h1>
        <button id="inc" onclick={increment}>Count: {count}</button>
        <button id="reset" onclick={reset} disabled={count == 0}>Reset</button>
        <label>
            Step <input id="step" type="number" bind={step} />
        </label>
        <p id="doubled">Doubled: {doubled}</p>
    </main>

#What runs where

Output of pyweb inspect: every page variable, handler and server function, where it runs and why.

Output
page Home  route=/
  browser  count          reactive state: assigned in increment(); literal initial value
  browser  step           reactive state: bound to an input (line 23); literal initial value
  browser  doubled        derived from count; recomputed when they change
  browser  increment      event handler (compiled to JavaScript)
  browser  reset          event handler (compiled to JavaScript)

#Generated JavaScript

The browser modules the compiler wrote (before minification). They import the shared runtime.

JavaScript
// Home.js
import { h as $h, t as $t, dyn as $dyn, list as $list, when as $when, signal as $signal, computed as $computed, mount as $mount, onMount as $onMount, py as $py, rpc as $rpc, subscribe as $subscribe, slot as $slot, onCleanup as $onCleanup, live as $live } from "./runtime.js";
function Home($s) {
  const count = $signal("count" in $s ? $s["count"] : 0);
  const step = $signal("step" in $s ? $s["step"] : 1);
  const doubled = $computed(() => $py.mul(count(), 2));
  function increment() {
    count($py.add(count(), step()));
  }
  function reset() {
    count(0);
  }
  return [$h("main", null, () => [
      $h("h1", null, () => [$t("Counter")]),
      $h("button", {"id": "inc", "onclick": increment}, () => [
        $t("Count: "),
        $dyn(() => count())
      ]),
      $h("button", {"id": "reset", "onclick": reset, "disabled": () => (count() === 0)}, () => [$t("Reset")]),
      $h("label", null, () => [
        $t("Step "),
        $h("input", {"id": "step", "type": "number", "$bind": step})
      ]),
      $h("p", {"id": "doubled"}, () => [
        $t("Doubled: "),
        $dyn(() => doubled())
      ])
    ])];
}
$mount("Home", Home);
Edit this page on GitHub