Skip to content

Bridge

The Python half of the native bridge: the ctypes binding to the renderer core, JSON codec, per-platform transports, protocol handshake, and the single callback the core and the platform use to reach Python. App code never calls this module directly; the BridgeBackend, BridgeModule, and NativeScreenHost do.

The bridge: Python's channel to the renderer core and the native platform.

Commits, layout reads, view commands, and animation requests go to the renderer core (include/pn_core.h), which every target links: the iOS app binary, Android's libpncore.so, the pythonnative._core host extension, and the browser preview's WebAssembly build. Native module calls go to the platform. Everything native sends back arrives at native_callback. The protocol is documented in docs/concepts/bridge.md.

Under pn preview the core and the widgets run in a browser page, reached through WebTransport; the preview installs it with set_transport before any screen mounts. Headless tests use FakeTransport, which runs the host build of the same core and plays the platform's UI thread in Python.

Modules:

Name Description
android

Android transport: libpncore.so through ctypes, modules through Chaquopy.

codec

JSON encoding for the native bridge.

core

The renderer core's C ABI, bound with ctypes (see RFC 0007).

fake

The host renderer core with Python playing the platform's UI thread.

ios

iOS transport: the renderer core and PythonNativeKit through ctypes.

web

WebSocket transport for the browser preview.

Classes:

Name Description
Transport

The Python -> core and Python -> platform half of the bridge.

Functions:

Name Description
get_transport

Return the active transport, creating the platform one on first use.

has_transport

Whether a transport exists or can be created without raising.

set_transport

Install a transport explicitly (tests) or reset with None.

contract_document

Encode every registered component and module contract as one document (tooling and tests).

handshake

Verify the native library speaks our protocol version.

native_callback

Single entry point for every native -> Python message.

dispatch

Handle one native -> Python message on the application thread.

Attributes:

Name Type Description
PROTOCOL_VERSION

The protocol include/pn_core.h defines as PN_CORE_PROTOCOL_VERSION.

PROTOCOL_VERSION module-attribute

PROTOCOL_VERSION = 8

The protocol include/pn_core.h defines as PN_CORE_PROTOCOL_VERSION.

Transport

Bases: Protocol

The Python -> core and Python -> platform half of the bridge.

Methods:

Name Description
protocol_version

Return the protocol version compiled into the renderer core.

load_contracts

Compile the merged component contracts into the core.

commit

Validate, apply, and lay out one commit; returns its acknowledgement.

layout

Lay out without a commit; returns {"ok", "value": layout}.

command

Queue a view command; its result arrives as a command message.

motion

Queue a motion request behind pending mounts (RFC 0009).

shared_read

The latest value the UI thread published for a shared value, as JSON.

measure

The shadow and window frames of a view, as JSON.

call

Call a native module method with a {"call_id", "args"} envelope.

set_callback

Install callback as the native -> Python entry point.

protocol_version

protocol_version() -> int

Return the protocol version compiled into the renderer core.

load_contracts

load_contracts(document: str) -> None

Compile the merged component contracts into the core.

commit

commit(envelope_json: str) -> str

Validate, apply, and lay out one commit; returns its acknowledgement.

layout

layout(request_json: str) -> str

Lay out without a commit; returns {"ok", "value": layout}.

command

command(
    surface: int,
    tag: int,
    name: str,
    args_json: str,
    call_id: int,
) -> str

Queue a view command; its result arrives as a command message.

motion

motion(surface: int, request_json: str) -> str

Queue a motion request behind pending mounts (RFC 0009).

shared_read

shared_read(ident: int) -> str

The latest value the UI thread published for a shared value, as JSON.

measure

measure(surface: int, tag: int) -> str

The shadow and window frames of a view, as JSON.

call

call(
    module: str, method: str, args_json: str
) -> Optional[str]

Call a native module method with a {"call_id", "args"} envelope.

set_callback

set_callback(
    callback: Callable[[str, int, str, str], None],
) -> None

Install callback as the native -> Python entry point.

get_transport

get_transport() -> Transport

Return the active transport, creating the platform one on first use.

Raises:

Type Description
RuntimeError

Off-device, where no native runtime exists.

has_transport

has_transport() -> bool

Whether a transport exists or can be created without raising.

set_transport

set_transport(transport: Optional[Transport]) -> None

Install a transport explicitly (tests) or reset with None.

contract_document

contract_document() -> str

Encode every registered component and module contract as one document (tooling and tests).

ensure_contracts

ensure_contracts(
    transport: Optional[Transport] = None,
) -> None

Compile newly registered contracts into transport's core before they're used.

The core validates native module calls as well as commits, so this runs at the handshake, before any module call, and again whenever a plugin registers a component or module.

handshake

handshake() -> int

Verify the native library speaks our protocol version.

Called by the native templates right after Python starts. Returns the negotiated version.

Raises:

Type Description
RuntimeError

On a version mismatch, with a hint to rebuild.

native_callback

native_callback(
    kind: str, tag: int, name: str, payload: str
) -> None

Single entry point for every native -> Python message.

The core and the platform deliver every message asynchronously, from an events thread, and never wait for a result. This function never raises: failures are reported through diagnostics so nothing propagates into UIKit or the Android looper.

Parameters:

Name Type Description Default
kind str

"event", "module", "host", "animation", "layout", or "command".

required
tag int

View tag (events), screen id (host), otherwise 0.

required
name str

Event name, module name, or host event.

required
payload str

JSON text whose shape depends on kind.

required

dispatch

dispatch(
    kind: str,
    tag: int,
    name: str,
    payload: str,
    backend: Any = None,
) -> None

Handle one native -> Python message on the application thread.

backend defaults to the process's view backend; headless backends pass themselves, since a test may keep several alive at once.

Renderer core

The C ABI of the renderer core (native/core/include/pn_core.h), bound with ctypes, plus Python decoders for its binary mount transactions and motion writes. On iOS the symbols come from the app binary, on Android from libpncore.so (named by PN_CORE_LIBRARY), and on the development machine from the pythonnative._core extension.

The renderer core's C ABI, bound with ctypes (see RFC 0007).

Every target links the same C++ core: the iOS app binary, Android's libpncore.so, the pythonnative._core extension on the development machine, and the browser preview's WebAssembly build. Python commits to it directly; the core validates each commit, lays it out with Yoga, flattens layout-only views, and queues binary mount transactions for the platform's UI thread. include/pn_core.h documents the functions and formats.

Strings the core returns are copied here and released with pn_core_free. ctypes releases the GIL for the duration of each call, so a commit's layout runs without holding it.

Classes:

Name Description
Platform

Python implementations of the platform callbacks (host and tests).

MountOp

One decoded mount transaction op (see include/pn_core.h).

MotionWrite

One record of the core's motion writes (RFC 0009).

MountTransaction

A decoded transaction: its surface, revision, id, and ops.

RendererCore

The bound C ABI of one loaded core library.

Functions:

Name Description
decode_transaction

Decode a mount transaction (the platform layer's job, done in Python for tests).

decode_writes

Decode the core's motion writes into MotionWrite records.

load_core

Return the process's renderer core, loading the library on first use.

PROTOCOL_VERSION module-attribute

PROTOCOL_VERSION = 8

The protocol include/pn_core.h defines as PN_CORE_PROTOCOL_VERSION.

Platform

Platform(
    schedule_mount: Callable[[], None] = lambda: None,
    schedule_work: Callable[[], None] = lambda: None,
    request_frames: Callable[[], None] = lambda: None,
    measure: Callable[
        [
            int,
            int,
            str,
            int,
            dict[str, Any],
            float,
            int,
            float,
            int,
        ],
        Tuple[float, float],
    ] = lambda surface, tag, component, mode, props, width, width_mode, height, height_mode: (
        0.0,
        0.0,
    ),
    baseline: Callable[
        [int, int, float, float], float
    ] = lambda surface, tag, width, height: height,
    emit: Callable[
        [str, int, int, str, str], None
    ] = lambda kind, surface, tag, name, payload: None,
)

Bases: _Record

Python implementations of the platform callbacks (host and tests).

On iOS and Android the platform layer is Swift or Kotlin and registers itself; a Python platform exists only where Python plays the UI thread. Every callback defaults to a no-op (baseline to the bottom edge).

MountOp

MountOp(
    kind: str,
    tag: int = 0,
    component: str = "",
    props: Optional[dict[str, Any]] = None,
    removed: Tuple[str, ...] = (),
    recreate: bool = False,
    parent: int = 0,
    index: int = 0,
    frame: Tuple[float, float, float, float] = (
        0.0,
        0.0,
        0.0,
        0.0,
    ),
    name: str = "",
    arguments: Any = None,
    call_id: int = 0,
    owner: int = 0,
)

Bases: _Record

One decoded mount transaction op (see include/pn_core.h).

owner is set on exit ops: 0 when the core animates the view out, 1 when the platform does.

MotionWrite

MotionWrite(
    kind: str,
    tag: int = 0,
    prop: str = "",
    value: Any = None,
    frame: Tuple[float, float, float, float] = (
        0.0,
        0.0,
        0.0,
        0.0,
    ),
    tags: Tuple[int, ...] = (),
)

Bases: _Record

One record of the core's motion writes (RFC 0009).

kind is "prop" (tag, prop, value), "frame" (tag, frame), or "remove" (tags: an exit finished, destroy each, children first).

MountTransaction

MountTransaction(
    surface: int,
    revision: int,
    id: int,
    ops: Tuple[MountOp, ...],
)

Bases: _Record

A decoded transaction: its surface, revision, id, and ops.

RendererCore

RendererCore(library: Any)

The bound C ABI of one loaded core library.

Python only uses the process-wide core (pn_core_shared), so every method passes that handle implicitly.

Methods:

Name Description
protocol_version

The protocol compiled into the loaded library.

load_contracts

Compile the merged contract document for platform.

fingerprint

The fingerprint of the loaded contracts.

set_flattening

Turn view flattening on or off (PN_FLATTEN=0 turns it off).

reset

Forget every surface, transaction, and contract (tests and reloads).

set_platform

Install Python platform callbacks (host and test cores only).

commit

Validate and apply one commit envelope; returns the acknowledgement JSON.

layout

Lay out without a commit; returns {"ok", "value": layout} JSON.

command

Queue a view command; the result arrives later as a command message.

motion

Queue a motion request behind pending mounts (RFC 0009).

shared_read

The latest published value of a shared value, as JSON.

worklet_eval

Run one worklet outside the runtime and return the result JSON.

measure

The shadow frame and window frame of tag as JSON ("null" when unknown).

inspect

The deepest view at a point, as JSON.

validate_module

Whether a native module call's arguments satisfy its contract.

work

Run deferred native-initiated work (relayout after a container resize).

check_value

Whether a JSON value satisfies a JSON-schema contract, as the core checks props.

mount_next

Take the next transaction's bytes and id, or None.

mount_finished

Report a transaction applied (or failed).

is_mounted

Whether the UI side holds a view for tag.

report_container

Report the size and window origin of a detached root's container.

report_intrinsic

Report a leaf's loaded content size (an image).

invalidate

Re-measure one leaf.

invalidate_measurements

Re-measure every leaf.

event

Stamp and deliver a view event, as the platform layer does.

animation_frame

Advance animations; returns whether more frames are needed.

take_writes

Motion writes produced since the last call.

exit_finished

Report a platform-owned exit (a leaving screen or modal) finished.

shared_elements

The views sharing a shared_tag between two screens, as JSON.

set_reduce_motion

Finish every animation at its target, as the platform's setting asks.

pointer

Feed (phase, pointer, x, y, window_x, window_y, time) events to a view's gestures.

gesture_deadline

When a view's gestures next need polling, or None.

gesture_poll

Advance a view's time-based gestures (long press, multi-tap windows).

has_gestures

Whether the core recognizes gestures for a view.

list_apply

Publish a list's next dataset patch on the UI side; returns its edits.

list_revision

The UI side's published dataset revision for a list (0 before the first).

list_keys

The UI side's keys for a list.

list_rows

The UI side's (key, revision, extent, sticky) rows for a list.

protocol_version

protocol_version() -> int

The protocol compiled into the loaded library.

load_contracts

load_contracts(document: str, platform: str) -> None

Compile the merged contract document for platform.

Raises:

Type Description
RuntimeError

When the document is malformed or conflicts.

fingerprint

fingerprint() -> str

The fingerprint of the loaded contracts.

set_flattening

set_flattening(enabled: bool) -> None

Turn view flattening on or off (PN_FLATTEN=0 turns it off).

reset

reset() -> None

Forget every surface, transaction, and contract (tests and reloads).

set_platform

set_platform(platform: Platform) -> None

Install Python platform callbacks (host and test cores only).

commit

commit(envelope: str) -> str

Validate and apply one commit envelope; returns the acknowledgement JSON.

layout

layout(request: str) -> str

Lay out without a commit; returns {"ok", "value": layout} JSON.

command

command(
    surface: int,
    tag: int,
    name: str,
    arguments: str,
    call_id: int,
) -> str

Queue a view command; the result arrives later as a command message.

motion

motion(surface: int, request: str) -> str

Queue a motion request behind pending mounts (RFC 0009).

shared_read

shared_read(ident: int) -> str

The latest published value of a shared value, as JSON.

worklet_eval

worklet_eval(request: str) -> str

Run one worklet outside the runtime and return the result JSON.

measure

measure(surface: int, tag: int) -> str

The shadow frame and window frame of tag as JSON ("null" when unknown).

inspect

inspect(surface: int, x: float, y: float) -> str

The deepest view at a point, as JSON.

validate_module

validate_module(
    module: str, method: str, arguments: str
) -> bool

Whether a native module call's arguments satisfy its contract.

work

work() -> None

Run deferred native-initiated work (relayout after a container resize).

check_value

check_value(schema: str, value: str) -> bool

Whether a JSON value satisfies a JSON-schema contract, as the core checks props.

mount_next

mount_next() -> Optional[Tuple[bytes, int]]

Take the next transaction's bytes and id, or None.

mount_finished

mount_finished(
    ident: int, error: Optional[str] = None
) -> None

Report a transaction applied (or failed).

is_mounted

is_mounted(surface: int, tag: int) -> bool

Whether the UI side holds a view for tag.

report_container

report_container(
    surface: int,
    tag: int,
    x: float,
    y: float,
    width: float,
    height: float,
) -> None

Report the size and window origin of a detached root's container.

report_intrinsic

report_intrinsic(
    surface: int, tag: int, width: float, height: float
) -> None

Report a leaf's loaded content size (an image).

invalidate

invalidate(surface: int, tag: int) -> None

Re-measure one leaf.

invalidate_measurements

invalidate_measurements() -> None

Re-measure every leaf.

event

event(
    surface: int,
    tag: int,
    name: str,
    arguments: str,
    edit_revision: int = 0,
) -> None

Stamp and deliver a view event, as the platform layer does.

animation_frame

animation_frame(timestamp_ms: float) -> bool

Advance animations; returns whether more frames are needed.

take_writes

take_writes() -> List[MotionWrite]

Motion writes produced since the last call.

exit_finished

exit_finished(surface: int, tag: int) -> None

Report a platform-owned exit (a leaving screen or modal) finished.

shared_elements

shared_elements(
    surface: int, from_screen: int, to_screen: int
) -> str

The views sharing a shared_tag between two screens, as JSON.

set_reduce_motion

set_reduce_motion(enabled: bool) -> None

Finish every animation at its target, as the platform's setting asks.

pointer

pointer(
    surface: int,
    tag: int,
    events: Sequence[
        Tuple[int, int, float, float, float, float, float]
    ],
) -> bool

Feed (phase, pointer, x, y, window_x, window_y, time) events to a view's gestures.

gesture_deadline

gesture_deadline(surface: int, tag: int) -> Optional[float]

When a view's gestures next need polling, or None.

gesture_poll

gesture_poll(surface: int, tag: int, time: float) -> None

Advance a view's time-based gestures (long press, multi-tap windows).

has_gestures

has_gestures(surface: int, tag: int) -> bool

Whether the core recognizes gestures for a view.

list_apply

list_apply(surface: int, tag: int) -> Optional[str]

Publish a list's next dataset patch on the UI side; returns its edits.

list_revision

list_revision(surface: int, tag: int) -> int

The UI side's published dataset revision for a list (0 before the first).

list_keys

list_keys(surface: int, tag: int) -> List[str]

The UI side's keys for a list.

list_rows

list_rows(
    surface: int, tag: int
) -> List[Tuple[str, int, float, bool]]

The UI side's (key, revision, extent, sticky) rows for a list.

decode_transaction

decode_transaction(data: bytes) -> MountTransaction

Decode a mount transaction (the platform layer's job, done in Python for tests).

decode_writes

decode_writes(data: bytes) -> List[MotionWrite]

Decode the core's motion writes into MotionWrite records.

decode_value

decode_value(data: bytes) -> Any

Decode one encoded value (measurement requests carry props this way).

load_core

load_core() -> RendererCore

Return the process's renderer core, loading the library on first use.

Setting PN_FLATTEN=0 in the environment mounts every view, which helps when a native view debugger should show the whole tree.

Codec

JSON encoding for the native bridge.

The bridge speaks JSON in both directions (see docs/concepts/bridge.md). Prop values coming out of the reconciler are almost, but not quite, JSON: they may contain frozenset event-name sets, tuples, floats that are infinite, and Python callables that native must never see. to_jsonable normalizes a value into something json.dumps accepts. Callbacks and declared Python-only fields stay in the backend's sidecar; unsupported native values raise an error.

Functions:

Name Description
to_jsonable

Return a JSON-serializable copy of value.

split_props

Split props into (wire_props, python_props).

build_transaction

Build the wire operations for a mutation batch, JSON-ready but not yet serialized.

dumps

Compact json.dumps used for every bridge payload.

loads

Parse a bridge payload (str or UTF-8 bytes); empty / None input yields None.

Attributes:

Name Type Description
INF

Wire spelling of math.inf (JSON has no infinity literal).

NEG_INF

Wire spelling of -math.inf.

INF module-attribute

INF = 'inf'

Wire spelling of math.inf (JSON has no infinity literal).

NEG_INF module-attribute

NEG_INF = '-inf'

Wire spelling of -math.inf.

to_jsonable

to_jsonable(value: Any) -> Any

Return a JSON-serializable copy of value.

  • set / frozenset / tuple become lists (sets are sorted when their members are strings so the output is deterministic).
  • Infinite floats become the strings "inf" / "-inf"; NaN becomes None (native clamps missing geometry to zero).
  • Dataclass-like objects with to_json() are converted through it.

Raises:

Type Description
TypeError

When value (or something nested in it) has no JSON representation.

split_props

split_props(
    props: Dict[str, Any],
    python_only: frozenset[str] = frozenset(),
) -> Tuple[Dict[str, Any], Dict[str, Any]]

Split props into (wire_props, python_props).

wire_props is JSON-ready; python_props holds callbacks and fields explicitly declared Python-only. Other unsupported values fail encoding. The backend keeps Python props in a per-tag sidecar. (The reconciler has already turned worklet handlers and animated styles into _pn_motion bindings before props reach the codec.)

build_transaction

build_transaction(
    ops: Sequence[Mutation],
    types: Mapping[int, str] | None = None,
) -> Tuple[List[Any], List[Tuple[int, Dict[str, Any]]]]

Build the wire operations for a mutation batch, JSON-ready but not yet serialized.

Parameters:

Name Type Description Default
ops Sequence[Mutation]

Ordered mutations from the reconciler.

required
types Mapping[int, str] | None

Native component names for tags, used to identify Python-only props.

None

Returns:

Type Description
List[Any]

(wire_ops, python_props) where wire_ops is the list the

List[Tuple[int, Dict[str, Any]]]

transaction envelope carries under "ops" (every value already

Tuple[List[Any], List[Tuple[int, Dict[str, Any]]]]

normalized by to_jsonable)

Tuple[List[Any], List[Tuple[int, Dict[str, Any]]]]

and python_props lists (tag, props) pairs for values that

Tuple[List[Any], List[Tuple[int, Dict[str, Any]]]]

stayed Python-side (for c and u ops). The backend removes

Tuple[List[Any], List[Tuple[int, Dict[str, Any]]]]

sidecar entries using UNSET values in the original update

Tuple[List[Any], List[Tuple[int, Dict[str, Any]]]]

operations.

dumps

dumps(value: Any) -> str

Compact json.dumps used for every bridge payload.

loads

loads(text: Union[str, bytes, bytearray, None]) -> Any

Parse a bridge payload (str or UTF-8 bytes); empty / None input yields None.

Fake transport (tests)

The host core with Python playing the platform's UI thread. See Testing what the platform mounts.

The host renderer core with Python playing the platform's UI thread.

FakeTransport commits to the host build of the same C++ core the apps link, so tests see the shipping validation, layout, flattening, list datasets, animation, and gestures. It mounts each transaction right away into a small tree of FakeNativeView objects, so tests can assert on what the platform would have mounted: created types and props, insert order, frames, commands, animated writes, and module calls. It also lets tests play the native side, firing events, pointers, and module results back into Python.

Every transport owns one core surface, so several can live in one test. They share the process's core and one Python platform, which routes each surface's mounts, measurements, and messages to its transport. Display frames for animations run as timers on the framework loop, so a FakeClock drives them.

Classes:

Name Description
FakeNativeView

One mounted view: type, merged props, mounted children, frame, and animated values.

FakeTransport

Commit to the host core and record what the UI thread would mount.

Functions:

Name Description
reset_fakes

Forget every fake surface and the core's state (the pytest plugin calls this between tests).

Attributes:

Name Type Description
DEFAULT_MEASURE Dict[str, Tuple[float, float]]

What the fake platform measures for content-sized leaves (and reports for loaded images).

ModuleHandler module-attribute

ModuleHandler = Callable[[str, Dict[str, Any]], Any]

handler(method, args) -> value for a fake native module.

DEFAULT_MEASURE module-attribute

DEFAULT_MEASURE: Dict[str, Tuple[float, float]] = {
    "Text": (60.0, 16.0),
    "Button": (80.0, 32.0),
    "Image": (40.0, 40.0),
    "TextInput": (120.0, 32.0),
    "TabBar": (320.0, 49.0),
}

What the fake platform measures for content-sized leaves (and reports for loaded images).

FakeNativeView

FakeNativeView(
    tag: int, type_name: str, props: Dict[str, Any]
)

One mounted view: type, merged props, mounted children, frame, and animated values.

Methods:

Name Description
presented

The value the platform shows for key: motion's write, else the committed prop.

Attributes:

Name Type Description
animated Dict[str, Any]

Paint props motion wrote, overriding props (RFC 0009).

exiting Optional[int]

The exit op's owner while the view animates out, else None.

animated instance-attribute

animated: Dict[str, Any] = {}

Paint props motion wrote, overriding props (RFC 0009).

exiting instance-attribute

exiting: Optional[int] = None

The exit op's owner while the view animates out, else None.

presented

presented(key: str) -> Any

The value the platform shows for key: motion's write, else the committed prop.

FakeTransport

FakeTransport(
    *,
    surface: int = 1,
    version: int = PROTOCOL_VERSION,
    measure: Optional[
        Dict[str, Tuple[float, float]]
    ] = None,
    core: Optional[RendererCore] = None
)

Commit to the host core and record what the UI thread would mount.

Parameters:

Name Type Description Default
surface int

The core surface this transport's backend commits to (1, the device surface, by default).

1
measure Optional[Dict[str, Tuple[float, float]]]

Sizes the fake platform measures, by component name.

None

Attributes:

Name Type Description
core

The bound host core.

views Dict[int, FakeNativeView]

Mounted views by tag (flattened views never appear).

transactions List[MountTransaction]

Every decoded mount transaction.

commands List[Tuple[int, str, Dict[str, Any]]]

(tag, name, args) tuples in the order the UI thread ran them.

writes List[MotionWrite]

Every MotionWrite, in order.

calls List[Tuple[str, str, Dict[str, Any]]]

(module, method, args) tuples in call order.

measured List[Tuple[int, str]]

(tag, component) pairs the core asked the platform to measure.

Methods:

Name Description
bind

Route this surface's messages to backend unless a callback was installed.

owns

Whether tag was ever mounted on this transport's surface.

protocol_version

Return the protocol version compiled into the renderer core.

set_callback

Install callback as the native -> Python entry point.

load_contracts

Compile the merged component contracts into the host core.

commit

Commit, then mount the resulting transaction as the UI thread would.

layout

Lay out without a commit and mount the frames.

command

Queue a view command and run it on the fake UI thread.

motion

Queue a motion request and apply it on the fake UI thread.

shared_read

The latest value the fake UI thread published for a shared value, as JSON.

exit_finished

Finish a platform-owned exit (a leaving screen or modal), as the native stack would.

shared_elements

The views the core pairs by shared_tag between two screens.

measure

The shadow and window frames of a view.

call

Call a native module method with a {"call_id", "args"} envelope.

drain

Mount queued transactions and run the core's deferred work until both are idle.

fire

Emit a view event as the platform would, through the core's stamping.

pointer

Feed (phase, pointer, x, y, window_x, window_y, time) events to a view's gestures.

gesture_deadline

When a view's gestures next need polling, or None.

poll_gestures

Advance time-based gestures for one view (long press, multi-tap windows).

report_container

Report a detached root's container size and relayout.

report_intrinsic

Report a loaded image's size and relayout.

invalidate

Re-measure one leaf and relayout.

emit_module_event

Push an unsolicited module event (AppState change, ...) into Python.

resolve_pending

Settle a call that returned pending.

host_event

Deliver a screen lifecycle event as the native host would.

find

Every mounted view whose type is type_name, in creation order.

roots

Mounted views with no parent (the attached screen roots and detached subtrees).

list_keys

The keys the UI thread's data source holds for a list.

list_rows

The (key, revision, extent, sticky) rows the UI thread holds for a list.

pending

Sentinel a module handler returns to answer pending.

measurer instance-attribute

measurer: Optional[
    Callable[
        [int, str, Dict[str, Any], float, float],
        Tuple[float, float],
    ]
] = None

Optional (tag, component, props, max_width, max_height) -> size override.

finish_exits instance-attribute

finish_exits = True

Finish platform-owned exits (leaving screens and modals) as soon as they mount.

reports_images instance-attribute

reports_images = True

Report each mounted Image's measured size as if it loaded, as a platform loader would.

animating property

animating: bool

Whether display frames are scheduled for running animations.

bind

bind(backend: Any) -> None

Route this surface's messages to backend unless a callback was installed.

owns

owns(tag: int) -> bool

Whether tag was ever mounted on this transport's surface.

protocol_version

protocol_version() -> int

Return the protocol version compiled into the renderer core.

set_callback

set_callback(
    callback: Callable[[str, int, str, str], None],
) -> None

Install callback as the native -> Python entry point.

load_contracts

load_contracts(document: str) -> None

Compile the merged component contracts into the host core.

commit

commit(envelope_json: str) -> str

Commit, then mount the resulting transaction as the UI thread would.

layout

layout(request_json: str) -> str

Lay out without a commit and mount the frames.

command

command(
    surface: int,
    tag: int,
    name: str,
    args_json: str,
    call_id: int,
) -> str

Queue a view command and run it on the fake UI thread.

motion

motion(surface: int, request_json: str) -> str

Queue a motion request and apply it on the fake UI thread.

shared_read

shared_read(ident: int) -> str

The latest value the fake UI thread published for a shared value, as JSON.

exit_finished

exit_finished(tag: int) -> None

Finish a platform-owned exit (a leaving screen or modal), as the native stack would.

shared_elements

shared_elements(
    from_screen: int, to_screen: int
) -> List[Dict[str, Any]]

The views the core pairs by shared_tag between two screens.

measure

measure(surface: int, tag: int) -> str

The shadow and window frames of a view.

call

call(
    module: str, method: str, args_json: str
) -> Optional[str]

Call a native module method with a {"call_id", "args"} envelope.

drain

drain() -> None

Mount queued transactions and run the core's deferred work until both are idle.

fire

fire(
    tag: int, name: str, *args: Any, edit_revision: int = 0
) -> None

Emit a view event as the platform would, through the core's stamping.

pointer

pointer(
    tag: int,
    events: Sequence[
        Tuple[int, int, float, float, float, float, float]
    ],
) -> bool

Feed (phase, pointer, x, y, window_x, window_y, time) events to a view's gestures.

gesture_deadline

gesture_deadline(tag: int) -> Optional[float]

When a view's gestures next need polling, or None.

poll_gestures

poll_gestures(tag: int, time: float) -> None

Advance time-based gestures for one view (long press, multi-tap windows).

report_container

report_container(
    tag: int,
    width: float,
    height: float,
    x: float = 0.0,
    y: float = 0.0,
) -> None

Report a detached root's container size and relayout.

report_intrinsic

report_intrinsic(
    tag: int, width: float, height: float
) -> None

Report a loaded image's size and relayout.

invalidate

invalidate(tag: int) -> None

Re-measure one leaf and relayout.

emit_module_event

emit_module_event(
    module: str, event: str, payload: Any = None
) -> None

Push an unsolicited module event (AppState change, ...) into Python.

resolve_pending

resolve_pending(
    call_id: int,
    value: Any = None,
    *,
    error: Optional[str] = None
) -> None

Settle a call that returned pending.

host_event

host_event(
    screen: int, event: str, payload: Any = None
) -> None

Deliver a screen lifecycle event as the native host would.

find

find(type_name: str) -> List[FakeNativeView]

Every mounted view whose type is type_name, in creation order.

roots

roots() -> List[FakeNativeView]

Mounted views with no parent (the attached screen roots and detached subtrees).

list_keys

list_keys(tag: int) -> List[str]

The keys the UI thread's data source holds for a list.

list_rows

list_rows(tag: int) -> List[Tuple[str, int, float, bool]]

The (key, revision, extent, sticky) rows the UI thread holds for a list.

pending staticmethod

pending() -> object

Sentinel a module handler returns to answer pending.

reset_fakes

reset_fakes() -> None

Forget every fake surface and the core's state (the pytest plugin calls this between tests).

Bootstrap

Entry point the native app templates run right after Python starts.

Both templates call start once the interpreter is up, on a background thread at launch:

pythonnative.bootstrap.start(dev, True, "app.main")

It connects the two halves of the bridge (installing the native -> Python callback on iOS), verifies the protocol version, routes print() to the console on iOS, warms the asyncio runtime, in debug builds starts the dev client that syncs sources from pn start, and imports the entry module, so the first screen only has to render. Along the way it records the startup timeline's contracts, bridge, and app marks (see startup_timeline). From then on the native runtime drives everything through callback("host", ...); see docs/concepts/bridge.md.

Functions:

Name Description
start

Connect the bridge and prepare the runtime.

status

Return the result of the last start (empty before it ran).

start

start(
    dev: bool = False,
    strict: bool = False,
    entry: Optional[str] = None,
) -> Dict[str, Any]

Connect the bridge and prepare the runtime.

Parameters:

Name Type Description Default
dev bool

Enable dev mode (RedBox, validation warnings, the dev client). Debug templates pass True.

False
strict bool

Re-raise the failure after recording it. The templates pass True so a broken bridge surfaces as a bootstrap error screen with the full traceback.

False
entry Optional[str]

The app's entry module, imported last so a broken app fails here with its traceback, and so the first screen doesn't pay for the import.

None

Returns:

Type Description
Dict[str, Any]

A status dict ({"protocol": 2, "platform": "ios"}) that the

Dict[str, Any]

template logs. Unless strict is set this never raises:

Dict[str, Any]

failures are printed and reported in the dict under

Dict[str, Any]

"error".

status

status() -> Dict[str, Any]

Return the result of the last start (empty before it ran).

Next steps