Diagnostics¶
Developer-mode warnings and error reporting. This module powers the
feedback you get while developing: [PN] WARN messages for suspicious
props and styles, the HookOrderError
raised on conditional hooks, and the RedBox overlay that surfaces
uncaught errors from renders, effects, and event handlers.
Dev mode is enabled automatically by pn start / pn preview and in
the debug builds pn run produces, or explicitly with the PN_DEV=1
environment variable.
In production builds every check in this module is skipped, so
shipping apps pay no overhead.
from pythonnative import diagnostics
if diagnostics.is_dev():
diagnostics.warn("fetching from a staging endpoint")
Most apps never call this module directly; it exists so framework code (and custom component libraries) can report problems in a way that reaches the developer instead of disappearing into a log.
Startup timeline¶
Every launch, in release builds too, logs one line to the device log once the first screen's first commit is acknowledged:
[PN] startup: framework 182 ms, contracts 9 ms, bridge 30 ms, app 310 ms, render 41 ms, commit 28 ms, total 640 ms
startup_timeline returns
the same numbers as a dict, and a running
profiler records them as
startup.<phase>_ms gauges. The docstring below says what each phase
covers.
Developer diagnostics: dev mode, warnings, and error reporting.
PythonNative distinguishes dev mode (the pn preview window, pn
run with hot reload, or any process with PN_DEV=1) from production.
Dev mode turns on:
- Validation warnings (
warn/warn_once): unknown style keys, duplicate list keys, and similar mistakes are printed once with a suggestion instead of failing silently. - Hook-order checking: calling hooks conditionally corrupts slot
state; in dev mode the mismatch raises a
HookOrderErrorimmediately instead of cross-wiring state. - The RedBox: uncaught errors from render, effects, and event
handlers are routed to the screen host, which presents a full-screen
error overlay (see
pythonnative.hosts) instead of crashing or swallowing the traceback.
In production none of this runs: validation is skipped, hook-order checks are skipped, and errors propagate exactly as raised.
The startup timeline runs in every build: each launch logs one
[PN] startup: line, and
startup_timeline returns
the same phases.
This module has no dependencies on the rest of PythonNative, so any module (hooks, reconciler, events) may import it freely.
Classes:
| Name | Description |
|---|---|
HookOrderError |
Raised in dev mode when hooks are called in a different order than the previous render. |
Functions:
| Name | Description |
|---|---|
set_dev_mode |
Explicitly enable or disable dev mode for this process. |
reset_dev_mode |
Return to the mode the |
is_dev |
Return whether dev diagnostics are active. |
log |
Print a framework trace line ( |
begin_startup |
Set the |
mark_startup |
Record that startup |
startup_timeline |
Return how long each startup phase of this process took, in milliseconds. |
startup_summary |
The timeline as the one-line form logged at launch ( |
warn |
Print a dev warning and record it in the warning log. |
warn_once |
Like |
swallowed |
Surface a suppressed native-backend exception (dev mode only). |
get_warnings |
Return a snapshot of the recorded warnings (oldest first). |
clear_warnings |
Drop all recorded warnings and dedupe keys (test helper). |
set_error_reporter |
Register or unregister |
add_listener |
Receive every warning and reported error as an |
set_error_handler |
Receive every uncaught error, in development and release builds alike. |
handle_error |
Tell the app's error handler about |
report_error |
Give |
Attributes:
| Name | Type | Description |
|---|---|---|
STARTUP_PHASES |
The startup phases, in launch order (see |
STARTUP_PHASES
module-attribute
¶
The startup phases, in launch order (see startup_timeline).
HookOrderError
¶
Bases: RuntimeError
Raised in dev mode when hooks are called in a different order than the previous render.
Hooks map to state slots by call order, so calling them inside conditionals or loops (or returning early between hook calls) silently cross-wires state in production. Dev mode detects the mismatch and raises this error with the offending component and slot so the bug is caught at the source.
set_dev_mode
¶
set_dev_mode(enabled: bool) -> None
Explicitly enable or disable dev mode for this process.
Called automatically by pn preview and by the screen host's
enable_hot_reload (which the device templates invoke on debug
builds). An explicit call wins over the PN_DEV environment
variable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
enabled
|
bool
|
|
required |
reset_dev_mode
¶
Return to the mode the PN_DEV environment variable selects.
is_dev
¶
is_dev() -> bool
Return whether dev diagnostics are active.
An explicit set_dev_mode
call wins; otherwise the PN_DEV environment variable, read when
this module is imported, decides (default False).
log
¶
log(message: str) -> None
Print a framework trace line ([PN] message) in dev mode.
The reconciler and screen hosts call this at phase boundaries (mount, re-render, RedBox) so a dev console shows what the runtime is doing. No-op in production.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The trace text. |
required |
begin_startup
¶
begin_startup(origin: float) -> None
Set the time.perf_counter() value the framework phase starts from.
pythonnative/__init__.py calls this with the time it started
executing, before it records the framework mark.
mark_startup
¶
Record that startup phase finished now; only the first mark of each phase counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
phase
|
str
|
One of |
required |
since
|
Optional[float]
|
The |
None
|
commit counts only once render is recorded. When it is, the
timeline is complete: it's reported through the profiling gauges
(startup.<phase>_ms) and, after a launch through
pythonnative.bootstrap, logged as one [PN] startup: line, in
release builds too.
startup_timeline
¶
Return how long each startup phase of this process took, in milliseconds.
Keys appear in launch order, and only for the phases recorded so far:
framework:import pythonnative, from the first line of the package's__init__to its last. Interpreter startup before it isn't included.contracts: starting the runtime and loading the native contracts compiled into the app (bootstrap.start).bridge: the protocol handshake and the view backend.app: the dev client (debug builds) and importing the app's entry module.render: the first screen's first render, from the start of its mount.commit: from the end of that render until the native side acknowledged the first commit.total: from the start ofimport pythonnativeuntil that acknowledgment, including time between the phases (the native screen being created, for example). Present oncecommitis.
A process that didn't launch through pythonnative.bootstrap (a
test, the browser preview) records only the phases it ran.
Returns:
| Type | Description |
|---|---|
Dict[str, float]
|
A new |
startup_summary
¶
startup_summary() -> str
The timeline as the one-line form logged at launch (startup: framework 182 ms, ...).
warn
¶
warn(message: str) -> None
Print a dev warning and record it in the warning log.
No-op in production. Warnings are prefixed with [PN] WARN on
stderr and retained (most recent 200) for inspection via
get_warnings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Human-readable description of the problem, ideally with a suggestion for the fix. |
required |
warn_once
¶
Like warn, but at most once per key.
Use for per-render validation (style keys, list keys) so a warning fires once instead of sixty times a second.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
The warning message. |
required |
key
|
Optional[str]
|
Dedupe key, e.g. |
None
|
swallowed
¶
swallowed(context: str) -> None
Surface a suppressed native-backend exception (dev mode only).
The native view/module backends intentionally degrade gracefully in
production: a failed style application or a missing OS API must not
crash the app. Call this from the except block instead of
pass so that, in dev mode, each suppression is reported once per
call site instead of disappearing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
str
|
Where the suppression happened, e.g.
|
required |
get_warnings
¶
Return a snapshot of the recorded warnings (oldest first).
set_error_reporter
¶
set_error_reporter(
owner: Any,
reporter: Optional[
Callable[[BaseException, str], None]
],
) -> None
Register or unregister owner's RedBox reporter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
owner
|
Any
|
Any object identifying the registration (a screen
host); keyed by |
required |
reporter
|
Optional[Callable[[BaseException, str], None]]
|
|
required |
add_listener
¶
Receive every warning and reported error as an ErrorReport.
The devtools agent subscribes so warnings and errors reach the DevTools Problems panel with their component stacks. Reports are only built while a listener is registered, and only in dev mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
callback
|
Callable[[Any], None]
|
Called with an
|
required |
Returns:
| Type | Description |
|---|---|
Callable[[], None]
|
A callable that removes the listener. |
notify_error
¶
notify_error(exc: BaseException, phase: str) -> None
Tell listeners about an error shown in the error screen or terminal.
set_error_handler
¶
set_error_handler(
handler: Optional[Callable[[BaseException, str], None]],
) -> None
Receive every uncaught error, in development and release builds alike.
This is where a crash reporter attaches. handler gets the exception and
the phase it came from ("render", "effect", "event", "async",
"mount", and similar). It runs on the application thread and should
return quickly. An error it raises itself is printed and dropped. Errors a
boundary of your own catches don't arrive here; use its on_error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
Optional[Callable[[BaseException, str], None]]
|
The callback, or |
required |
handle_error
¶
handle_error(exc: BaseException, phase: str) -> None
Tell the app's error handler about exc, at most once per exception.
report_error
¶
report_error(
exc: BaseException, phase: str = "runtime"
) -> bool
Give exc to the app's error handler, and to the RedBox reporter in dev mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exc
|
BaseException
|
The exception to display. |
required |
phase
|
str
|
Where it came from: |
'runtime'
|
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
reporter is registered (or dev mode is off), in which case the |
bool
|
caller should fall back to its default behavior. |
Next steps¶
- Catch render errors in the tree with
ErrorBoundary: see the Error boundaries guide. - The rules of hooks and what
HookOrderErrormeans: Hooks.