Skip to content

Components

Element factory functions for the built-in PythonNative widgets. These return immutable Element descriptors; nothing is mounted to a native view tree until the Reconciler processes them.

Containers take their children positionally as *children: pn.Node, and every other argument is a keyword argument on the factory, which makes it part of the generated native contract for iOS, Android, and the browser preview. Keywords shared by many components are declared once as shared props instead of in every factory. Platform notes (an Android-only ripple, an iOS-only keyboard appearance) are recorded on the argument itself. Event callbacks receive the typed payloads below rather than dicts, and a ref= argument receives a typed handle after commit.

For the visual and layout properties accepted by each component's style argument, see the Component Property Reference.

Built-in element factories.

Each factory function (Text, Button, …) is a fully-typed thin wrapper that builds an Element through the shared _make_element helper, so style resolution, ref attachment, None-default dropping, and forced overrides (e.g. Column's fixed flex_direction) live in exactly one place. The factory signatures themselves are the canonical prop schemas: editors and type checkers validate calls directly against them.

The factories are grouped by concern into submodules (text, media, controls, layout, pressable, overlays, structural, lists); everything public is re-exported here, so from pythonnative.components import Text keeps working.

Example
import pythonnative as pn

pn.Column(
    pn.Text("Hello", style=pn.style(font_size=18)),
    pn.Button("Tap", on_press=lambda: print("tapped")),
    style=pn.style(gap=12, padding=16),
)

Modules:

Name Description
controls

Form controls and side-effect elements.

events

Typed event payloads delivered by the built-in components.

graphics

Graphics factories: Svg, LinearGradient, and BlurView.

layout

Container factories: View, Column, Row, Spacer, ScrollView, and the inset-aware wrappers.

lists

Keyed virtualized lists with one logical component tree.

media

Media factories: Image, ImageBackground, and WebView.

overlays

Overlay factories: Modal (native presentation) and Portal (window overlay).

pressable

Touch wrappers: Pressable and its TouchableOpacity alias.

props

Props shared by the built-in components, declared once as TypedDicts.

structural

Structural factories: Fragment, ErrorBoundary, and Suspense.

text

Text-centric leaf factories: Text, Button, and TextInput.

Classes:

Name Description
ListController

Imperative scroll handle published on a list's ref.

PressState

The interaction state handed to Pressable's callable style and child.

Ripple

Android's material ripple drawn while a Pressable is pressed.

Functions:

Name Description
ActivityIndicator

Show an indeterminate loading spinner.

Checkbox

A boolean checkbox with an optional inline label.

DatePicker

A native date / time picker.

Picker

A real native dropdown / select widget.

ProgressBar

Show determinate progress as a value between 0.0 and 1.0.

RefreshControl

Pull-to-refresh control for ScrollView and the list components.

SegmentedControl

A horizontal multi-choice control (one selected segment at a time).

Slider

Continuous-value slider between min_value and max_value.

StatusBar

Configure the device's status bar appearance.

Switch

Display a toggle switch.

BlurView

A container that blurs whatever is drawn behind it.

LinearGradient

A container filled with a linear color gradient.

Svg

Draw vector shapes in a single native view.

Column

Arrange children vertically.

KeyboardAvoidingView

Wrap content that should shift up when the keyboard is shown.

Row

Arrange children horizontally.

SafeAreaView

Container that respects safe-area insets (notch, status bar, home indicator).

ScrollView

Wrap children in a scrollable container.

Spacer

Insert empty space inside a flex container.

View

Universal flex container (like React Native's View).

FlatList

Virtualized scrollable list that renders items from data lazily.

SectionList

Virtualized list with section headers interleaved between row groups.

Image

Display a bundled, local, or remote image.

ImageBackground

Render children layered on top of a background image.

WebView

Embed web content from a URL or an inline HTML string.

Modal

Overlay modal dialog backed by a real native presentation.

Portal

Render children into a full-screen overlay above everything else.

Pressable

Wrap children with tap / long-press / gesture handlers.

TouchableOpacity

Wrap children so they fade to active_opacity while pressed.

ErrorBoundary

Catch render errors in the wrapped subtree and display fallback instead.

Fragment

Group children without adding a wrapping native view.

Suspense

Show fallback while descendants wait on async work, then swap in the content.

Button

Display a tappable button.

Text

Display a string of text, optionally with styled nested spans.

TextInput

Display a text-entry field (single-line by default, or multiline).

Attributes:

Name Type Description
BlurType

Backdrop material styles for BlurView.

PreserveAspectRatio

How an Svg view box scales into a frame of a different aspect ratio.

ImageSource

What Image.source accepts: a URL, data: URI, file path, or bundled Asset.

EllipsizeMode

Where Text truncates when it exceeds max_lines.

KeyboardAppearance

TextInput.keyboard_appearance value (iOS keyboard theme).

BlurType module-attribute

BlurType = Literal[
    "light",
    "dark",
    "regular",
    "prominent",
    "extra_light",
    "system_thin_material",
    "system_material",
    "system_thick_material",
    "system_chrome_material",
]

Backdrop material styles for BlurView.

PreserveAspectRatio module-attribute

PreserveAspectRatio = Literal['meet', 'slice', 'none']

How an Svg view box scales into a frame of a different aspect ratio.

ImageSource module-attribute

ImageSource = Union[str, Asset]

What Image.source accepts: a URL, data: URI, file path, or bundled Asset.

EllipsizeMode module-attribute

EllipsizeMode = Literal['head', 'middle', 'tail', 'clip']

Where Text truncates when it exceeds max_lines.

KeyboardAppearance module-attribute

KeyboardAppearance = Literal['default', 'light', 'dark']

TextInput.keyboard_appearance value (iOS keyboard theme).

ListController

ListController(
    scroll_to_offset: Callable[[float, bool], None],
    scroll_to_index: Callable[[int, bool], None],
    scroll_to_end: Callable[[bool], None],
)

Imperative scroll handle published on a list's ref.

FlatList and SectionList install a ListController on ref.current (via use_imperative_handle) after mount and clear it back to None on unmount. Commands go through the inner VirtualList's ViewHandle.

Example
import pythonnative as pn

@pn.component
def Chat(messages):
    list_ref = pn.use_ref()
    pn.use_layout_effect(
        lambda: list_ref.current and list_ref.current.scroll_to_end(animated=False),
        [len(messages)],
    )
    return pn.FlatList(data=messages, render_item=Bubble, ref=list_ref)

Methods:

Name Description
scroll_to_offset

Scroll to an absolute content offset in points.

scroll_to_index

Scroll so the row at index sits at the top of the viewport.

scroll_to_end

Scroll to the end of the content.

scroll_to_offset

scroll_to_offset(
    offset: float, animated: bool = True
) -> None

Scroll to an absolute content offset in points.

scroll_to_index

scroll_to_index(index: int, animated: bool = True) -> None

Scroll so the row at index sits at the top of the viewport.

scroll_to_end

scroll_to_end(animated: bool = True) -> None

Scroll to the end of the content.

PressState dataclass

PressState(pressed: bool)

The interaction state handed to Pressable's callable style and child.

Attributes:

Name Type Description
pressed bool

Whether a finger is currently down on the view.

Ripple dataclass

Ripple(
    color: Color,
    borderless: bool = False,
    radius: Optional[float] = None,
    foreground: bool = False,
)

Android's material ripple drawn while a Pressable is pressed.

Passed as android_ripple=; iOS and the browser preview ignore it (use pressed_opacity or a callable style for feedback there).

Attributes:

Name Type Description
color Color

Ripple color.

borderless bool

Draw the ripple beyond the view's bounds (a circle around the touch point) instead of clipping it.

radius Optional[float]

Ripple radius in dp, or the view's size when None.

foreground bool

Draw the ripple over the children instead of behind them.

ActivityIndicator

ActivityIndicator(
    *,
    animating: bool = True,
    color: Optional[Color] = None,
    size: Literal["small", "large"] = "small",
    style: StyleProp = None,
    key: Optional[str] = None
) -> Element

Show an indeterminate loading spinner.

Parameters:

Name Type Description Default
animating bool

When False, the spinner is hidden.

True
color Optional[Color]

Spinner color.

None
size Literal['small', 'large']

"small" (default) or "large".

'small'
style StyleProp

Style dict (or list of dicts).

None
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element of type

Element

"ActivityIndicator".

Checkbox

Checkbox(
    *,
    value: bool = False,
    on_change: Optional[Callable[[bool], Any]] = None,
    label: Optional[str] = None,
    disabled: bool = False,
    color: Optional[Color] = None,
    style: StyleProp = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

A boolean checkbox with an optional inline label.

Backed by android.widget.CheckBox on Android and a checkmark UIButton on iOS. Tapping the control (or its label) toggles the value and fires on_change(new_value).

Parameters:

Name Type Description Default
value bool

Current checked state.

False
on_change Optional[Callable[[bool], Any]]

Callback invoked with the new boolean state.

None
label Optional[str]

Optional text shown beside the box (also tappable).

None
disabled bool

When True, the control is greyed out and inert.

False
color Optional[Color]

Tint applied to the checked box.

None
style StyleProp

Style dict (or list of dicts).

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "Checkbox".

DatePicker

DatePicker(
    *,
    value: Optional[str] = None,
    mode: Literal["date", "time", "datetime"] = "date",
    on_change: Optional[Callable[[str], Any]] = None,
    minimum: Optional[str] = None,
    maximum: Optional[str] = None,
    disabled: bool = False,
    style: StyleProp = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

A native date / time picker.

Backed by UIDatePicker on iOS and a trigger button that opens the platform DatePickerDialog / TimePickerDialog on Android. value and the value reported to on_change are ISO-8601 strings ("2026-05-31" for mode="date", "14:30" for mode="time", "2026-05-31T14:30" for mode="datetime"), so values stay JSON-serializable and platform-agnostic.

Parameters:

Name Type Description Default
value Optional[str]

Currently selected value as an ISO-8601 string.

None
mode Literal['date', 'time', 'datetime']

"date" (default), "time", or "datetime".

'date'
on_change Optional[Callable[[str], Any]]

Callback invoked with the new ISO-8601 string.

None
minimum Optional[str]

Earliest selectable value (ISO-8601), if any.

None
maximum Optional[str]

Latest selectable value (ISO-8601), if any.

None
disabled bool

When True, the picker is disabled.

False
style StyleProp

Style dict (or list of dicts).

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "DatePicker".

Picker

Picker(
    *,
    value: Any = None,
    disabled: bool = False,
    items: Optional[List[Dict[str, Any]]] = None,
    on_change: Optional[Callable[[Any], Any]] = None,
    placeholder: str = "Select…",
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

A real native dropdown / select widget.

Renders a tappable trigger labelled with the selected item; the iOS handler attaches a UIMenu (system dropdown) and the Android handler uses a native Spinner. Selecting an item fires on_change(value).

items is an ordered list of {"value": Any, "label": str} entries (label defaults to str(value) when omitted).

Parameters:

Name Type Description Default
disabled bool

Whether the control ignores user input.

False
value Any

Currently selected value (matched against items[i]["value"]).

None
items Optional[List[Dict[str, Any]]]

Selectable options.

None
on_change Optional[Callable[[Any], Any]]

Callback invoked with the new value.

None
placeholder str

Label shown when no item matches value.

'Select…'
style StyleProp

Style dict applied to the trigger.

None
ref Optional[Ref]

Optional Ref from use_ref().

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "Picker".

ProgressBar

ProgressBar(
    *,
    value: float = 0.0,
    color: Optional[Color] = None,
    track_color: Optional[Color] = None,
    indeterminate: bool = False,
    style: StyleProp = None,
    key: Optional[str] = None
) -> Element

Show determinate progress as a value between 0.0 and 1.0.

For a spinner instead of a bar, use ActivityIndicator; for an indeterminate bar pass indeterminate=True.

Parameters:

Name Type Description Default
value float

Fraction complete (clamped to [0.0, 1.0] by the platform handler).

0.0
color Optional[Color]

Color of the filled portion of the bar.

None
track_color Optional[Color]

Color of the unfilled track behind the fill.

None
indeterminate bool

When True, the bar animates continuously and value is ignored.

False
style StyleProp

Style dict (or list of dicts).

None
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element of type "ProgressBar".

RefreshControl

RefreshControl(
    *,
    refreshing: bool = False,
    on_refresh: Optional[Callable[[], Any]] = None,
    tint_color: Optional[Color] = None
) -> Element

Pull-to-refresh control for ScrollView and the list components.

Pass the result as the refresh_control= prop of a ScrollView, FlatList, or SectionList. It is a regular Element (type "RefreshControl") built like every other piece of UI; the scroll container attaches it to its native scroll view rather than rendering it as a child, and rejects anything else with a TypeError.

Parameters:

Name Type Description Default
refreshing bool

Drive the spinner's visibility from a use_state value.

False
on_refresh Optional[Callable[[], Any]]

Callback invoked when the user pulls down past the threshold. Set refreshing to True for the duration of the work, then back to False on completion.

None
tint_color Optional[Color]

Color of the spinner.

None

Returns:

Type Description
Element

An Element of type "RefreshControl".

Example
import pythonnative as pn

@pn.component
def MyList():
    refreshing, set_refreshing = pn.use_state(False)

    def reload():
        set_refreshing(True)
        # ... fetch data ...
        set_refreshing(False)

    return pn.ScrollView(
        pn.Text("Pull me!"),
        refresh_control=pn.RefreshControl(
            refreshing=refreshing, on_refresh=reload
        ),
    )

SegmentedControl

SegmentedControl(
    *,
    segments: Optional[List[str]] = None,
    selected_index: int = 0,
    on_change: Optional[Callable[[int], Any]] = None,
    disabled: bool = False,
    tint_color: Optional[Color] = None,
    style: StyleProp = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

A horizontal multi-choice control (one selected segment at a time).

Backed by UISegmentedControl on iOS and a styled toggle row on Android. Selecting a segment fires on_change(index).

Parameters:

Name Type Description Default
segments Optional[List[str]]

Ordered list of segment labels.

None
selected_index int

Index of the currently selected segment.

0
on_change Optional[Callable[[int], Any]]

Callback invoked with the newly selected index.

None
disabled bool

When True, the control is disabled.

False
tint_color Optional[Color]

Accent color for the selected segment.

None
style StyleProp

Style dict (or list of dicts).

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type

Element

"SegmentedControl".

Slider

Slider(
    *,
    value: float = 0.0,
    min_value: float = 0.0,
    max_value: float = 1.0,
    on_change: Optional[Callable[[float], Any]] = None,
    disabled: bool = False,
    step: float = 0.0,
    minimum_track_color: Optional[Color] = None,
    maximum_track_color: Optional[Color] = None,
    thumb_color: Optional[Color] = None,
    on_sliding_start: Optional[
        Callable[[float], Any]
    ] = None,
    on_sliding_complete: Optional[
        Callable[[float], Any]
    ] = None,
    style: StyleProp = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

Continuous-value slider between min_value and max_value.

Parameters:

Name Type Description Default
value float

Current slider value.

0.0
min_value float

Lower bound.

0.0
max_value float

Upper bound.

1.0
on_change Optional[Callable[[float], Any]]

Callback invoked with the new value as the user drags.

None
disabled bool

Prevent dragging the slider.

False
step float

Snap values to this increment, or zero for continuous movement.

0.0
minimum_track_color Optional[Color]

Filled track color.

None
maximum_track_color Optional[Color]

Unfilled track color.

None
thumb_color Optional[Color]

Thumb color, or the platform default.

None
on_sliding_start Optional[Callable[[float], Any]]

Callback when the user starts dragging.

None
on_sliding_complete Optional[Callable[[float], Any]]

Callback when the user finishes dragging.

None
style StyleProp

Style dict (or list of dicts).

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "Slider".

StatusBar

StatusBar(
    *,
    bar_style: Optional[
        Literal["light", "dark", "default"]
    ] = None,
    background_color: Optional[Color] = None,
    hidden: Optional[bool] = None,
    translucent: bool = False,
    animated: bool = False,
    key: Optional[str] = None
) -> Element

Configure the device's status bar appearance.

StatusBar is a side-effect element: it doesn't render any visible content but applies its props to the host platform's status bar. Mount one near the top of your tree.

The bar_style parameter is named separately from the universal style kwarg (which is unused here) to avoid the conflict that style="light" would create with the visual-style dict used elsewhere.

Parameters:

Name Type Description Default
bar_style Optional[Literal['light', 'dark', 'default']]

"light" (light icons over dark backgrounds), "dark" (dark icons over light backgrounds), or "default" (system default).

None
background_color Optional[Color]

Color of the status-bar background (Android only; iOS draws the bar transparent over your content).

None
hidden Optional[bool]

When True, the status bar is hidden.

None
translucent bool

Draw your content under the status bar instead of below it (Android only; iOS always draws underneath).

False
animated bool

Animate bar_style and hidden changes (iOS only).

False
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element of type "StatusBar".

Switch

Switch(
    *,
    value: bool = False,
    on_change: Optional[Callable[[bool], Any]] = None,
    disabled: bool = False,
    on_tint_color: Optional[Color] = None,
    thumb_color: Optional[Color] = None,
    style: StyleProp = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

Display a toggle switch.

Parameters:

Name Type Description Default
value bool

Current on/off state.

False
on_change Optional[Callable[[bool], Any]]

Callback invoked with the new boolean state.

None
disabled bool

Prevent changes while keeping the switch visible.

False
on_tint_color Optional[Color]

Track color when the switch is on.

None
thumb_color Optional[Color]

Thumb color, or the platform default.

None
style StyleProp

Style dict (or list of dicts).

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "Switch".

BlurView

BlurView(
    *children: Node,
    blur_type: BlurType = "regular",
    intensity: float = 100.0,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

A container that blurs whatever is drawn behind it.

On iOS this is a UIVisualEffectView (blur_type selects the UIBlurEffect style). In the browser preview it is backdrop-filter. Android has no system backdrop blur, so the view snapshots the content beneath it at reduced resolution, blurs the snapshot, and tints it; it looks right for static backgrounds and approximates animated ones.

Parameters:

Name Type Description Default
*children Node

Content drawn over the blur.

()
blur_type BlurType

The material style. "light", "dark", and "regular" are portable; the system_* values map to the iOS 13 materials and fall back to the closest tint elsewhere.

'regular'
intensity float

Blur strength from 0 (transparent) to 100.

100.0
style StyleProp

Style dict (or list of dicts).

None
ref Optional[Ref]

Optional Ref from use_ref().

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "BlurView".

Example
pn.ImageBackground(
    pn.BlurView(pn.Text("Caption"), blur_type="dark", style=pn.style(padding=12)),
    source=pn.asset("images/hero.jpg"),
    style=pn.style(height=200, justify_content="flex-end"),
)

LinearGradient

LinearGradient(
    *children: Node,
    colors: Sequence[Color],
    locations: Optional[Sequence[float]] = None,
    start_point: Tuple[float, float] = (0.0, 0.0),
    end_point: Tuple[float, float] = (0.0, 1.0),
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

A container filled with a linear color gradient.

Lays out children exactly like View; the gradient is the background. start_point and end_point are unit coordinates in the view's box ((0, 0) top-left, (1, 1) bottom-right), so the defaults draw top to bottom.

Parameters:

Name Type Description Default
*children Node

Content drawn over the gradient.

()
colors Sequence[Color]

Two or more colors, in order from start_point to end_point.

required
locations Optional[Sequence[float]]

Optional stop positions in [0, 1], one per color. Evenly spaced when omitted.

None
start_point Tuple[float, float]

Unit point where the first color sits.

(0.0, 0.0)
end_point Tuple[float, float]

Unit point where the last color sits.

(0.0, 1.0)
style StyleProp

Style dict (or list of dicts); border_radius clips the gradient.

None
ref Optional[Ref]

Optional Ref from use_ref().

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "LinearGradient".

Raises:

Type Description
ValueError

If fewer than two colors are given or locations doesn't match colors in length.

Example
pn.LinearGradient(
    pn.Text("Welcome", style=pn.style(color="white", font_size=24)),
    colors=["#6366F1", "#EC4899"],
    start_point=(0, 0),
    end_point=(1, 1),
    style=pn.style(padding=24, border_radius=16),
)

Svg

Svg(
    *children: Any,
    shapes: Optional[Sequence[SvgShape]] = None,
    view_box: Optional[str] = None,
    preserve_aspect_ratio: PreserveAspectRatio = "meet",
    fill: Optional[Color] = None,
    stroke: Optional[Color] = None,
    stroke_width: Optional[float] = None,
    stroke_linecap: Optional[LineCap] = None,
    stroke_linejoin: Optional[LineJoin] = None,
    fill_rule: Optional[FillRule] = None,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

Draw vector shapes in a single native view.

Pass shapes from pythonnative.svg (Path, Circle, Rect, Line, Polyline, Polygon, Ellipse, and G groups) as children. Coordinates are in view_box units and are scaled into the view's frame. Without an explicit width and height in style, the view measures to the view box size.

Paint left unset on a shape inherits the root values here, then the SVG defaults (black fill, no stroke). Set fill="none" to draw outlines only.

Parameters:

Name Type Description Default
*children Any

Shapes and groups to draw, in paint order.

()
shapes Optional[Sequence[SvgShape]]

Pre-flattened shape records (what pn.svg.load produces). Combined with children.

None
view_box Optional[str]

"min-x min-y width height". Defaults to "0 0 24 24".

None
preserve_aspect_ratio PreserveAspectRatio

"meet" letterboxes, "slice" crops, "none" stretches.

'meet'
fill Optional[Color]

Default fill color for shapes that don't set one.

None
stroke Optional[Color]

Default stroke color.

None
stroke_width Optional[float]

Default stroke width in view box units.

None
stroke_linecap Optional[LineCap]

Default line cap.

None
stroke_linejoin Optional[LineJoin]

Default line join.

None
fill_rule Optional[FillRule]

Default fill rule.

None
style StyleProp

Style dict (or list of dicts). width and height set the drawn size; opacity and transforms apply as usual.

None
ref Optional[Ref]

Optional Ref from use_ref().

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "Svg".

Example
from pythonnative import svg

pn.Svg(
    svg.Circle(cx=12, cy=12, r=10, fill="#0EA5E9"),
    svg.Path(d="M8 12h8", stroke="white", stroke_width=2),
    view_box="0 0 24 24",
    style=pn.style(width=48, height=48),
)

Column

Column(
    *children: Node,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[ViewProps]
) -> Element

Arrange children vertically.

Convenience wrapper around View with flex_direction locked to "column". Use View directly if you need to switch between row and column at runtime.

Accepts every View prop (gestures, hit slop, accessibility, test_id); only flex_direction is fixed.

Parameters:

Name Type Description Default
*children Node

Child elements stacked top to bottom.

()
style StyleProp

Style dict (or list of dicts).

None
ref Optional[Ref]

Optional Ref for native-view access.

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[ViewProps]

Shared accessibility and test keywords; see ViewProps (layout, gestures, and accessibility).

{}

Returns:

Type Description
Element

An Element of type "Column".

KeyboardAvoidingView

KeyboardAvoidingView(
    *children: Node,
    behavior: Literal[
        "padding", "position", "height"
    ] = "padding",
    keyboard_vertical_offset: float = 0.0,
    style: StyleProp = None,
    key: Optional[str] = None
) -> Element

Wrap content that should shift up when the keyboard is shown.

Subscribes to the platform-reported keyboard height (via use_keyboard_height internally) and shifts its content so the focused text input stays visible. On iOS the height comes from UIKeyboardWillShowNotification; on Android from the window's IME insets.

Parameters:

Name Type Description Default
*children Node

Children rendered inside the avoiding container.

()
behavior Literal['padding', 'position', 'height']

"padding" (adds bottom padding, resizing the content), "position" (translates the container upward without resizing), or "height" (shrinks the container's height by the keyboard overlap, matching React Native's "height" behavior).

'padding'
keyboard_vertical_offset float

Distance in layout units already covered by other UI (e.g. a nav bar); subtracted from the keyboard height before applying the shift.

0.0
style StyleProp

Style dict (or list of dicts).

None
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element that renders a

Element

"KeyboardAvoidingView" container.

Row

Row(
    *children: Node,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[ViewProps]
) -> Element

Arrange children horizontally.

Convenience wrapper around View with flex_direction locked to "row". Use View directly if you need to switch between row and column at runtime.

Accepts every View prop (gestures, hit slop, accessibility, test_id); only flex_direction is fixed.

Parameters:

Name Type Description Default
*children Node

Child elements arranged left to right.

()
style StyleProp

Style dict (or list of dicts).

None
ref Optional[Ref]

Optional Ref for native-view access.

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[ViewProps]

Shared accessibility and test keywords; see ViewProps (layout, gestures, and accessibility).

{}

Returns:

Type Description
Element

An Element of type "Row".

SafeAreaView

SafeAreaView(
    *children: Node,
    edges: Optional[
        Tuple[
            Literal["top", "left", "bottom", "right"], ...
        ]
    ] = None,
    style: StyleProp = None,
    key: Optional[str] = None
) -> Element

Container that respects safe-area insets (notch, status bar, home indicator).

Applies the platform-reported insets as extra padding on the selected edges and re-renders automatically when the insets change (rotation, split view). User padding on an inset edge is added to the inset, matching react-native-safe-area-context.

Parameters:

Name Type Description Default
*children Node

Child elements that should avoid system UI overlays.

()
edges Optional[Tuple[Literal['top', 'left', 'bottom', 'right'], ...]]

Which edges to pad; defaults to all four.

None
style StyleProp

Style dict (or list of dicts).

None
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element that renders a

Element

"SafeAreaView" container.

ScrollView

ScrollView(
    *children: Node,
    horizontal: bool = False,
    refresh_control: Optional[Element] = None,
    content_container_style: StyleProp = None,
    content_inset: Optional[EdgeInsets] = None,
    scroll_enabled: bool = True,
    scroll_event_throttle: float = 16,
    on_scroll: Optional[
        Callable[[ScrollEvent], Any]
    ] = None,
    on_scroll_begin_drag: Optional[
        Callable[[ScrollEvent], Any]
    ] = None,
    on_scroll_end_drag: Optional[
        Callable[[ScrollEvent], Any]
    ] = None,
    on_momentum_scroll_end: Optional[
        Callable[[ScrollEvent], Any]
    ] = None,
    shows_scroll_indicator: bool = True,
    paging_enabled: bool = False,
    bounces: bool = True,
    keyboard_dismiss_mode: Optional[
        Literal["none", "on_drag", "interactive"]
    ] = None,
    keyboard_should_persist_taps: Literal[
        "never", "always", "handled"
    ] = "never",
    snap_to_interval: Optional[float] = None,
    snap_to_alignment: Literal[
        "start", "center", "end"
    ] = "start",
    deceleration_rate: Union[
        Literal["normal", "fast"], float
    ] = "normal",
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None
) -> Element

Wrap children in a scrollable container.

ScrollView typically takes a single child (a Column or Row aggregating the scrollable content). It accepts *children for ergonomic call sites; the underlying native scroll view stacks them on its content axis.

pn.ScrollView(
    *rows,
    content_container_style=pn.style(padding=16, gap=12),
    content_inset=pn.EdgeInsets(bottom=80),
    on_scroll=lambda e: print(e.y),
    keyboard_should_persist_taps="handled",
    keyboard_dismiss_mode="on_drag",
    ref=scroll_ref,
)

Parameters:

Name Type Description Default
*children Node

Child elements to scroll.

()
horizontal bool

Scroll along the x axis instead of the y axis.

False
refresh_control Optional[Element]

Optional RefreshControl element attached to the scroll view for pull-to-refresh.

None
content_container_style StyleProp

Style applied to the scrollable content (padding, gap, alignment), distinct from style (the scroll view frame). The children are wrapped in one inner View carrying this style, so every layout key works on every renderer.

None
content_inset Optional[EdgeInsets]

Extra scrollable space around the content, as an EdgeInsets; useful for keeping the last row clear of a floating footer.

None
scroll_enabled bool

When False, the user can't scroll (the content still lays out and imperative scrolling works).

True
scroll_event_throttle float

Minimum milliseconds between on_scroll callbacks while scrolling. Native emits on_scroll only when the app wired it.

16
on_scroll Optional[Callable[[ScrollEvent], Any]]

Callback invoked with a ScrollEvent as the user scrolls.

None
on_scroll_begin_drag Optional[Callable[[ScrollEvent], Any]]

Callback invoked with a ScrollEvent when the user's finger starts dragging.

None
on_scroll_end_drag Optional[Callable[[ScrollEvent], Any]]

Callback invoked with a ScrollEvent when the user's finger lifts.

None
on_momentum_scroll_end Optional[Callable[[ScrollEvent], Any]]

Callback invoked with a ScrollEvent when the deceleration after a fling comes to rest.

None
shows_scroll_indicator bool

When False, hides the scroll bar.

True
paging_enabled bool

When True, the scroll view snaps to multiples of its own size (carousel behavior).

False
bounces bool

When False, disables the iOS rubber-band overscroll.

True
keyboard_dismiss_mode Optional[Literal['none', 'on_drag', 'interactive']]

"none" (default), "on_drag", or "interactive". Controls whether scrolling dismisses the keyboard.

None
keyboard_should_persist_taps Literal['never', 'always', 'handled']

Whether a tap inside the scroll view dismisses the keyboard: "never" (the default; a tap dismisses it), "always" (never dismiss), or "handled" (dismiss only when nothing inside handled the tap).

'never'
snap_to_interval Optional[float]

Snap the resting offset to multiples of this many points (a carousel of fixed-size cards).

None
snap_to_alignment Literal['start', 'center', 'end']

Which edge of the viewport the snapped offset aligns to: "start", "center", or "end".

'start'
deceleration_rate Union[Literal['normal', 'fast'], float]

How quickly a fling comes to rest: "normal", "fast", or a per-millisecond factor (0.998 is normal, 0.99 is fast).

'normal'
style StyleProp

Style dict (or list of dicts).

None
ref Optional[Ref]

Optional Ref from use_ref(); receives a ScrollViewHandle.

None
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element of type "ScrollView".

Spacer

Spacer(
    *,
    size: Optional[float] = None,
    flex: Optional[float] = None,
    key: Optional[str] = None
) -> Element

Insert empty space inside a flex container.

Pass size for a fixed gap, or flex to expand and absorb remaining space.

Parameters:

Name Type Description Default
size Optional[float]

Fixed gap in dp/pt along the parent's main axis. Mirrored on both axes: whichever axis the parent's flex_direction chooses as main becomes the actual gap.

None
flex Optional[float]

Flex-grow weight; useful for pushing siblings to the opposite end of a Row or Column.

None
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element of type "Spacer".

View

View(
    *children: Node,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[ViewProps]
) -> Element

Universal flex container (like React Native's View).

Defaults to flex_direction: "column" (override via style).

Flex container properties (passed via style):

  • flex_direction: "column" (default), "row", "column_reverse", "row_reverse".
  • flex_wrap: "nowrap" (default), "wrap", "wrap_reverse", with align_content controlling how wrapped lines share leftover cross-axis space.
  • justify_content: main-axis distribution. Accepts "flex_start" (default), "center", "flex_end", "space_between", "space_around", "space_evenly".
  • align_items: cross-axis alignment. Accepts "stretch" (default), "flex_start", "center", "flex_end".
  • direction: "ltr" (default) or "rtl". Flips rows and resolves margin_start / padding_end / absolute start / end insets.
  • overflow: "visible" (default) or "hidden".
  • spacing (alias gap; per-axis row_gap / column_gap), padding, background_color, border_radius, border_width, border_color, shadow_color, shadow_offset, shadow_opacity, shadow_radius, elevation, opacity, transform.

Parameters:

Name Type Description Default
*children Node

Child elements rendered inside the container.

()
style StyleProp

Style dict (or list of dicts).

None
ref Optional[Ref]

Optional Ref from use_ref(); receives a ViewHandle.

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[ViewProps]

Shared accessibility and test keywords; see ViewProps (layout, gestures, and accessibility).

{}

Returns:

Type Description
Element

An Element of type "View".

FlatList

FlatList(
    *,
    data: Optional[Sequence[T]] = None,
    data_revision: int = 0,
    render_item: Optional[
        Callable[[T, int], Element]
    ] = None,
    key_extractor: Optional[
        Callable[[T, int], str]
    ] = None,
    item_height: Optional[float] = None,
    get_item_height: Optional[
        Callable[[T, int], float]
    ] = None,
    estimated_item_height: Optional[float] = None,
    separator_height: float = 0,
    item_separator: ItemSeparator = None,
    refresh_control: Optional[Element] = None,
    horizontal: bool = False,
    inverted: bool = False,
    num_columns: int = 1,
    initial_scroll_index: Optional[int] = None,
    list_header: Optional[Element] = None,
    list_footer: Optional[Element] = None,
    list_empty: Optional[Element] = None,
    on_end_reached: Optional[Callable[[], Any]] = None,
    on_end_reached_threshold: float = 0.5,
    on_viewable_items_changed: Optional[
        Callable[[List[ViewableItem[T]]], None]
    ] = None,
    on_scroll: Optional[
        Callable[[ScrollEvent], Any]
    ] = None,
    shows_scroll_indicator: bool = True,
    content_container_style: StyleProp = None,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None
) -> Element

Virtualized scrollable list that renders items from data lazily.

A bounded window of keyed row components supplies content to the renderer. UIKit collection views and Android recycler views own native cells; the browser implements the same row-request protocol. Headless backends simulate the same row requests. Rows may have variable heights: pass item_height when rows are uniform, get_item_height for exact per-item extents, or nothing at all; unknown rows start at estimated_item_height and are corrected with their measured extent once they've been on screen.

Pass a Ref (from use_ref) to receive a ListController on ref.current: ref.current.scroll_to_index(i), ref.current.scroll_to_offset(pts), and ref.current.scroll_to_end().

Parameters:

Name Type Description Default
data Optional[Sequence[T]]

A ListData source or a sequence of arbitrary item values. Use explicit mutations on ListData; replace ordinary sequences when they change.

None
data_revision int

Increment after changing a sequence in place. Unchanged sequence identity and revision reuse the indexed dataset.

0
render_item Optional[Callable[[T, int], Element]]

render_item(item, index) -> Element. Defaults to wrapping each item in a Text.

None
key_extractor Optional[Callable[[T, int], str]]

Function returning a stable key per item (recommended whenever data can reorder).

None
item_height Optional[float]

Uniform row extent in points, when known.

None
get_item_height Optional[Callable[[T, int], float]]

get_item_height(item, index) -> float for exact variable extents without measurement.

None
estimated_item_height Optional[float]

Starting extent estimate for rows whose true size isn't known yet (default 44).

None
separator_height float

Gap below each row, in points.

0
item_separator ItemSeparator

An element, or a zero-argument function returning one, rendered after every row except the last (React Native's ItemSeparatorComponent).

None
refresh_control Optional[Element]

Optional RefreshControl element for pull-to-refresh.

None
horizontal bool

Scroll horizontally (extents become widths).

False
inverted bool

Render the list bottom-up (or right-to-left when horizontal), so new rows appended to data appear at the visible end, as in a chat transcript. Implemented with a mirror transform on the list and on each row.

False
num_columns int

Render items in a grid of this many columns.

1
initial_scroll_index Optional[int]

Item index scrolled to, without animation, once the list mounts.

None
list_header Optional[Element]

Element rendered once before all rows.

None
list_footer Optional[Element]

Element rendered once after all rows.

None
list_empty Optional[Element]

Element rendered when data is empty.

None
on_end_reached Optional[Callable[[], Any]]

Called when the user scrolls within on_end_reached_threshold viewports of the end (fires once per dataset revision).

None
on_end_reached_threshold float

Distance from the end, in viewport multiples, at which on_end_reached fires.

0.5
on_viewable_items_changed Optional[Callable[[List[ViewableItem[T]]], None]]

Called with a list of frozen ViewableItem records whenever the set of visible rows changes.

None
on_scroll Optional[Callable[[ScrollEvent], Any]]

Called with a ScrollEvent as the list scrolls.

None
shows_scroll_indicator bool

When False, hides the scroll bar.

True
content_container_style StyleProp

Style applied to the inner content wrapper.

None
style StyleProp

Style for the outer scroll container.

None
ref Optional[Ref]

Optional Ref; receives a ListController on ref.current after mount.

None
key Optional[str]

Stable identity for keyed reconciliation of the list.

None

Returns:

Type Description
Element

A virtualized list element (a function component instance).

Example
import pythonnative as pn

items = [{"id": i, "name": f"Item {i}"} for i in range(10000)]

pn.FlatList(
    data=items,
    item_height=44,
    render_item=lambda item, _: pn.Text(item["name"]),
    key_extractor=lambda item, _: str(item["id"]),
)

SectionList

SectionList(
    *,
    sections: Optional[Sequence[Section[T]]] = None,
    data_revision: int = 0,
    render_item: Optional[
        Callable[[T, int, int], Element]
    ] = None,
    render_section_header: Optional[
        Callable[[Section[T], int], Element]
    ] = None,
    key_extractor: Optional[
        Callable[[Any, int], str]
    ] = None,
    item_height: Optional[float] = None,
    get_item_height: Optional[
        Callable[[Any, int, int], float]
    ] = None,
    estimated_item_height: Optional[float] = None,
    section_header_height: Optional[float] = None,
    separator_height: float = 0,
    item_separator: ItemSeparator = None,
    sticky_section_headers: bool = False,
    inverted: bool = False,
    refresh_control: Optional[Element] = None,
    list_header: Optional[Element] = None,
    list_footer: Optional[Element] = None,
    list_empty: Optional[Element] = None,
    on_end_reached: Optional[Callable[[], Any]] = None,
    on_end_reached_threshold: float = 0.5,
    on_viewable_items_changed: Optional[
        Callable[[List[ViewableItem[T]]], None]
    ] = None,
    on_scroll: Optional[
        Callable[[ScrollEvent], Any]
    ] = None,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None
) -> Element

Virtualized list with section headers interleaved between row groups.

Flattens sections into a single virtualized sequence where each entry is either a header or an item, then reuses the same windowing engine as FlatList; headers and items may have different (and variable) heights.

Parameters:

Name Type Description Default
data_revision int

Increment after changing sections in place to rebuild the indexed dataset.

0
sections Optional[Sequence[Section[T]]]

Each section is a Section(key=..., data=..., title=...) record.

None
render_item Optional[Callable[[T, int, int], Element]]

render_item(item, item_index, section_index) -> Element.

None
render_section_header Optional[Callable[[Section[T], int], Element]]

render_section_header(section, section_index) -> Element. Defaults to a bold Text of the section title.

None
key_extractor Optional[Callable[[Any, int], str]]

Stable key per item: key_extractor(item, item_index) -> str.

None
item_height Optional[float]

Uniform item extent in points, when known.

None
get_item_height Optional[Callable[[Any, int, int], float]]

get_item_height(item, item_index, section_index) -> float for exact variable extents.

None
estimated_item_height Optional[float]

Starting estimate for unmeasured rows.

None
section_header_height Optional[float]

Header extent in points, when known.

None
separator_height float

Gap below each item, in points.

0
item_separator ItemSeparator

An element, or a zero-argument function returning one, rendered between the items of each section.

None
sticky_section_headers bool

Keep the current section's header pinned at the top of the list while its items scroll by. Native layout pins the existing header and lets the next header push it away, without Python scroll callbacks.

False
inverted bool

Render the list bottom-up (see FlatList).

False
refresh_control Optional[Element]

Optional RefreshControl element.

None
list_header Optional[Element]

Element rendered once before everything.

None
list_footer Optional[Element]

Element rendered once after everything.

None
list_empty Optional[Element]

Element rendered when there are no sections.

None
on_end_reached Optional[Callable[[], Any]]

Called near the end of the content.

None
on_end_reached_threshold float

Distance from the end, in viewport multiples, at which on_end_reached fires.

0.5
on_viewable_items_changed Optional[Callable[[List[ViewableItem[T]]], None]]

Called with a list of frozen ViewableItem records (items only, with flat indices) whenever the set of visible rows changes.

None
on_scroll Optional[Callable[[ScrollEvent], Any]]

Called with a ScrollEvent as the list scrolls.

None
style StyleProp

Style for the outer scroll container.

None
ref Optional[Ref]

Optional Ref; receives a ListController on ref.current after mount.

None
key Optional[str]

Stable identity for keyed reconciliation of the list.

None

Returns:

Type Description
Element

A virtualized list element (a function component instance).

Image

Image(
    source: ImageSource = "",
    *,
    default_source: Optional[ImageSource] = None,
    scale_type: Optional[ScaleType] = None,
    tint_color: Optional[Color] = None,
    placeholder_color: Optional[Color] = None,
    blur_radius: Optional[float] = None,
    on_load_start: Optional[Callable[[], Any]] = None,
    on_load: Optional[
        Callable[[ImageLoadEvent], Any]
    ] = None,
    on_load_end: Optional[Callable[[], Any]] = None,
    on_error: Optional[Callable[[str], Any]] = None,
    fade_duration: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

Display a bundled, local, or remote image.

Style properties: background_color, border_*, opacity, transform, plus the common layout props.

Bundled images live under app/assets/ and are referenced with pn.asset; density variants (logo@2x.png, logo@3x.png) are picked for the device automatically and the image measures at its logical (1x) size.

Network images (http:// / https://) go through the shared native image pipeline: downloads happen on a background thread, bytes are cached in memory and on disk keyed by URL, concurrent requests for the same URL share one download, and large bitmaps are downsampled to the view size when decoded.

Parameters:

Name Type Description Default
source ImageSource

A bundled Asset, an http(s) URL, a data: URI, or an absolute file path.

''
default_source Optional[ImageSource]

A bundled or local image shown until source has loaded (and left in place if it fails). Must not be a network URL.

None
scale_type Optional[ScaleType]

Fit mode: "cover", "contain", "stretch", "center".

None
tint_color Optional[Color]

Color overlay applied to template images (monochrome icons).

None
placeholder_color Optional[Color]

Background color shown while a remote image is loading (and left in place if it fails).

None
blur_radius Optional[float]

Gaussian blur radius in logical points applied to the decoded image.

None
on_load_start Optional[Callable[[], Any]]

Callback invoked when loading begins (a network fetch or a decode).

None
on_load Optional[Callable[[ImageLoadEvent], Any]]

Callback invoked once the image has been decoded and displayed, with its logical width and height.

None
on_load_end Optional[Callable[[], Any]]

Callback invoked when loading finishes, after on_load or on_error.

None
on_error Optional[Callable[[str], Any]]

Callback invoked with an error message when a remote image fails to download or decode.

None
fade_duration Optional[float]

Milliseconds to cross-fade the image in once it has loaded (Android and the browser; iOS shows it at once).

None
headers Optional[Mapping[str, str]]

Extra HTTP headers sent with a network source (authorization, cache control).

None
style StyleProp

Style dict (or list of dicts).

None
ref Optional[Ref]

Optional Ref from use_ref().

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "Image".

ImageBackground

ImageBackground(
    *children: Node,
    source: ImageSource = "",
    scale_type: Optional[ScaleType] = None,
    style: StyleProp = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

Render children layered on top of a background image.

Composed entirely from existing primitives: an absolutely-filled Image sits behind a content View holding children. The container's style controls sizing/padding; the image stretches to fill it via position: "absolute" and zeroed insets.

Parameters:

Name Type Description Default
*children Node

Foreground content drawn over the image.

()
source ImageSource

A bundled Asset, URL, data: URI, or file path (see Image).

''
scale_type Optional[ScaleType]

Background fit mode ("cover" is the most common for backgrounds).

None
style StyleProp

Style dict for the container (size, padding, alignment).

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "View" wrapping

Element

the background image and foreground content.

WebView

WebView(
    *,
    url: str = "",
    html: Optional[str] = None,
    on_load: Optional[Callable[[str], Any]] = None,
    on_load_start: Optional[Callable[[str], Any]] = None,
    on_error: Optional[Callable[[str], Any]] = None,
    on_message: Optional[Callable[[str], Any]] = None,
    on_navigation_state_change: Optional[
        Callable[[WebNavigationEvent], Any]
    ] = None,
    inject_javascript: Optional[str] = None,
    scroll_enabled: bool = True,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None
) -> Element

Embed web content from a URL or an inline HTML string.

Parameters:

Name Type Description Default
url str

HTTP(S) URL to load. Ignored when html is given.

''
html Optional[str]

Inline HTML markup to render instead of loading a URL.

None
on_load Optional[Callable[[str], Any]]

Callback invoked with the final URL once a page finishes loading.

None
on_load_start Optional[Callable[[str], Any]]

Callback invoked with the URL when loading starts.

None
on_error Optional[Callable[[str], Any]]

Callback invoked with a top-level load error message.

None
on_message Optional[Callable[[str], Any]]

Callback invoked with the string payload whenever page JavaScript calls window.pythonnative.postMessage(...).

None
on_navigation_state_change Optional[Callable[[WebNavigationEvent], Any]]

Callback invoked with a typed navigation state when the top-level document starts or finishes loading.

None
inject_javascript Optional[str]

JavaScript evaluated after each page load (useful for installing the postMessage bridge or tweaking the DOM).

None
scroll_enabled bool

When False, disables scrolling inside the web content.

True
style StyleProp

Style dict (or list of dicts).

None
ref Optional[Ref]

Optional Ref from use_ref(); receives a WebViewHandle with reload(), go_back(), eval_js(), and friends.

None
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element of type "WebView".

Modal

Modal(
    *children: Node,
    visible: bool = False,
    on_dismiss: Optional[Callable[[], Any]] = None,
    on_show: Optional[Callable[[], Any]] = None,
    on_request_close: Optional[Callable[[], Any]] = None,
    title: Optional[str] = None,
    animation_type: Literal[
        "slide", "fade", "none"
    ] = "slide",
    transparent: bool = False,
    presentation_style: Literal[
        "page_sheet", "form_sheet", "full_screen", "overlay"
    ] = "page_sheet",
    dismiss_on_backdrop: bool = True,
    status_bar_translucent: bool = False,
    style: StyleProp = None,
    key: Optional[str] = None
) -> Element

Overlay modal dialog backed by a real native presentation.

The modal is shown when visible=True and hidden when False. Drive visible from a hook so the parent component can dismiss the modal in response to user actions. On iOS this presents a UIViewController; on Android it shows an android.app.Dialog.

Children are mounted as the modal's content view, not into the on-tree placeholder, so they appear above all other native content and don't influence the underlying layout.

Parameters:

Name Type Description Default
*children Node

Modal content.

()
visible bool

Controls whether the modal is presented.

False
on_dismiss Optional[Callable[[], Any]]

Callback invoked once the modal has closed after visible became False.

None
on_show Optional[Callable[[], Any]]

Callback invoked once the modal has finished presenting.

None
on_request_close Optional[Callable[[], Any]]

Callback invoked when the user asks to close the modal from outside your content: the Android back button, an iOS sheet pull-down, or a tap on an overlay's backdrop. Set visible=False in response; when unset the modal stays open.

None
title Optional[str]

Optional title-bar text.

None
animation_type Literal['slide', 'fade', 'none']

"slide" (default), "fade", or "none".

'slide'
transparent bool

When True, the underlying view is dimmed instead of fully covered.

False
presentation_style Literal['page_sheet', 'form_sheet', 'full_screen', 'overlay']

iOS presentation style, "page_sheet" (default), "form_sheet", "full_screen", or "overlay" (custom dimmed overlay). On Android, "overlay" keeps the dialog non-fullscreen.

'page_sheet'
dismiss_on_backdrop bool

When True (default), a tap on the dimmed backdrop of a transparent / "overlay" modal (outside its content) calls on_request_close. False ignores those taps and also locks an iOS sheet against the pull-down.

True
status_bar_translucent bool

Draw the modal under a translucent status bar (Android only).

False
style StyleProp

Style dict (or list of dicts).

None
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element of type "Modal".

Portal

Portal(
    *children: Node, key: Optional[str] = None
) -> Element

Render children into a full-screen overlay above everything else.

Like React DOM's createPortal: the children stay part of this component's tree for state, context, and events, but their native views mount in a transparent overlay attached to the window (above the screen's content) instead of inside the surrounding parent. Use it for toasts, dropdowns, tooltips, and lightweight custom overlays that must escape overflow: "hidden" ancestors. For a system-styled dialog with its own presentation and dismissal gestures, use Modal instead.

The overlay itself does not intercept touches; only the children themselves are hit-testable. Children are laid out against the full viewport, so position them with absolute insets:

pn.Portal(
    pn.View(
        pn.Text("Saved!"),
        style=pn.style(position="absolute", bottom=40, left=40, right=40),
    ),
)

Parameters:

Name Type Description Default
*children Node

Overlay content.

()
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element of type "Portal".

Pressable

Pressable(
    *children: Union[Node, Callable[[PressState], Node]],
    on_press: Optional[Callable[[], Any]] = None,
    on_long_press: Optional[Callable[[], Any]] = None,
    on_press_in: Optional[Callable[[], Any]] = None,
    on_press_out: Optional[Callable[[], Any]] = None,
    disabled: bool = False,
    delay_long_press: float = 500,
    pressed_opacity: float = 0.6,
    android_ripple: Optional[Ripple] = None,
    style: Union[
        StyleProp, Callable[[PressState], StyleProp]
    ] = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[ViewProps]
) -> Element

Wrap children with tap / long-press / gesture handlers.

Useful for making non-button elements (text, images, custom views) respond to user taps. The wrapper view fades to pressed_opacity on touch-down and back to full opacity on touch-up.

Pressable gets accessibility_role="button" by default.

pn.Pressable(
    lambda state: pn.Text("Pressed" if state.pressed else "Press me"),
    on_press=save,
    disabled=not valid,
    delay_long_press=400,
    android_ripple=pn.Ripple(color="#33000000"),
    style=lambda state: pn.style(opacity=0.5 if state.pressed else 1),
)

Parameters:

Name Type Description Default
*children Union[Node, Callable[[PressState], Node]]

Nodes to make pressable, or a single callable receiving the PressState and returning the child to render.

()
on_press Optional[Callable[[], Any]]

Callback invoked on a normal tap.

None
on_long_press Optional[Callable[[], Any]]

Callback invoked on a sustained press.

None
on_press_in Optional[Callable[[], Any]]

Callback invoked the moment the press starts.

None
on_press_out Optional[Callable[[], Any]]

Callback invoked when the press lifts or cancels.

None
disabled bool

When True, no press callback fires and the view reports the disabled accessibility state (unless accessibility_state is given explicitly).

False
delay_long_press float

Milliseconds a press must be held before on_long_press fires.

500
pressed_opacity float

Opacity (0 to 1) applied while the user's finger is down. Set to 1.0 for no visual feedback.

0.6
android_ripple Optional[Ripple]

A Ripple drawn on Android while pressed; ignored on iOS and in the browser.

None
style Union[StyleProp, Callable[[PressState], StyleProp]]

Style dict applied to the wrapper, or a callable receiving the PressState and returning a style, re-evaluated on every press transition:

pn.Pressable(
    pn.Text("Tap"),
    style=lambda s: pn.style(
        background_color="#0051A8" if s.pressed else "#007AFF",
    ),
)
None
ref Optional[Ref]

Optional Ref from use_ref().

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[ViewProps]

Shared accessibility and test keywords; see ViewProps (layout, gestures, and accessibility).

{}

Returns:

Type Description
Element

An Element of type "Pressable"

Element

(wrapped in a stateful composite when style or the child

Element

is callable).

TouchableOpacity

TouchableOpacity(
    *children: Node,
    on_press: Optional[Callable[[], Any]] = None,
    on_long_press: Optional[Callable[[], Any]] = None,
    active_opacity: float = 0.2,
    disabled: bool = False,
    style: StyleProp = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

Wrap children so they fade to active_opacity while pressed.

A thin ergonomic alias over Pressable that mirrors React Native's TouchableOpacity: the only visual feedback is an opacity dip on touch-down. When disabled is set, the wrapper is inert and renders at reduced opacity.

Parameters:

Name Type Description Default
*children Node

Nodes to make tappable.

()
on_press Optional[Callable[[], Any]]

Callback invoked on a normal tap.

None
on_long_press Optional[Callable[[], Any]]

Callback invoked on a sustained press.

None
active_opacity float

Opacity (0 to 1) applied while the finger is down.

0.2
disabled bool

When True, ignores presses and renders at reduced opacity.

False
style StyleProp

Style dict applied to the wrapper.

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "Pressable".

ErrorBoundary

ErrorBoundary(
    *children: Node,
    fallback: Optional[Any] = None,
    on_error: Optional[
        Callable[[BaseException], Any]
    ] = None,
    key: Optional[str] = None
) -> Element

Catch render errors in the wrapped subtree and display fallback instead.

When any descendant raises during render (initial mount, a parent re-render, or a local state-driven update), the failed subtree is torn down and fallback is mounted in its place. Without a boundary the error propagates to the screen host (which shows the dev error overlay in dev mode).

fallback may be:

  • An Element, shown as-is.
  • fallback(error) -> Element.
  • fallback(error, reset) -> Element, where reset is a zero-arg callable that clears the error and remounts the original children (fresh state), for retry buttons.

Parameters:

Name Type Description Default
*children Node

Subtree to wrap.

()
fallback Optional[Any]

Fallback content (see above). Required for the boundary to actually catch; without it errors propagate to the next boundary up.

None
on_error Optional[Callable[[BaseException], Any]]

Callback invoked with the exception when the boundary catches, before the fallback mounts. Use it for error reporting.

None
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element whose type is

Element
Element

fallback and on_error in its props (omitted when

Element

None).

Example
import pythonnative as pn

pn.ErrorBoundary(
    MyRiskyComponent(),
    fallback=lambda err, reset: pn.Column(
        pn.Text(f"Error: {err}"),
        pn.Button("Retry", on_press=reset),
    ),
    on_error=lambda err: log.exception(err),
)

Fragment

Fragment(
    *children: Optional[Element], key: Optional[str] = None
) -> Element

Group children without adding a wrapping native view.

Like React's <></>: groups elements without introducing an extra container. Each child mounts as a direct sibling of the Fragment's position in the parent's child list. Components may also simply return a plain list of elements; Fragment exists for when the group needs a key (e.g. rendering a list of pairs) or when a single expression reads better.

pn.Column(
    pn.Text("Top"),
    pn.Fragment(
        pn.Text("Middle A"),
        pn.Text("Middle B"),
    ),
    pn.Text("Bottom"),
)

Parameters:

Name Type Description Default
*children Optional[Element]

Child elements to expose at the parent level. None and False children are dropped, which makes conditional rendering with cond and pn.Text(...) ergonomic.

()
key Optional[str]

Stable identity for keyed reconciliation. A keyed Fragment moves all of its children as one unit and preserves their state across reorders.

None

Returns:

Type Description
Element

An Element whose type is

Element

Suspense

Suspense(
    *children: Node,
    fallback: Optional[Any] = None,
    key: Optional[str] = None
) -> Element

Show fallback while descendants wait on async work, then swap in the content.

A Suspense boundary catches suspensions from the subtree it wraps: an async def component body blocking on a pending await, or a regular component calling Resource.read on data that hasn't arrived (see use_resource and lazy). While anything is pending the boundary renders fallback; when the awaited work completes it retries the content and swaps it in. Suspended components keep their hook state across retries, so cached resources aren't refetched.

Two timing behaviors, matching React:

  • Initial mount: the fallback shows until the content is ready.
  • Updates: a component that's already on screen and suspends again (its dependencies changed) keeps its previous content visible and re-renders when ready; there's no fallback flash.

Parameters:

Name Type Description Default
*children Node

Subtree to wrap (the async content).

()
fallback Optional[Any]

Content shown while suspended: an Element or a zero-arg callable returning one. Without it, suspensions propagate to the next Suspense boundary up.

None
key Optional[str]

Stable identity for keyed reconciliation.

None

Returns:

Type Description
Element

An Element whose type is

Element

SUSPENSE, with fallback

Element

in its props.

Example
import pythonnative as pn

@pn.component
async def Profile(user_id: str):
    user = await api.fetch_user(user_id)
    return pn.Text(user.name)

@pn.component
def Screen():
    return pn.Suspense(
        Profile(user_id="42"),
        fallback=pn.ActivityIndicator(),
    )

Button

Button(
    title: str = "",
    *,
    on_press: Optional[Callable[[], Any]] = None,
    disabled: bool = False,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

Display a tappable button.

Style properties: color, background_color, font_size, border_radius, border_width, border_color, shadow_*, opacity, transform, plus the common layout props.

Buttons get accessibility_role="button" by default.

Parameters:

Name Type Description Default
title str

Button label.

''
on_press Optional[Callable[[], Any]]

Callback invoked when the user taps the button.

None
disabled bool

When True, the button is disabled and cannot be tapped.

False
style StyleProp

Style dict (or list of dicts).

None
ref Optional[Ref]

Optional Ref from use_ref().

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "Button".

Text

Text(
    *parts: Any,
    on_press: Optional[Callable[[], Any]] = None,
    ellipsize_mode: EllipsizeMode = "tail",
    selectable: bool = False,
    allow_font_scaling: bool = True,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

Display a string of text, optionally with styled nested spans.

Style properties: font_size, color, bold, font_weight, font_family, italic, text_align, background_color, max_lines, letter_spacing, line_height, text_decoration ("underline" / "line_through"), border_radius, border_width, border_color, shadow_*, opacity, transform, plus the common layout props.

Rich text: pass multiple parts, mixing plain strings and nested Text elements, to render one paragraph with per-span styling (a single TextView / UILabel natively, so line wrapping flows across spans). A nested span may carry its own on_press:

pn.Text(
    "Read the ",
    pn.Text("terms", on_press=open_terms, style=pn.style(color="#06F")),
    ".",
    max_lines=2,
    ellipsize_mode="tail",
    selectable=True,
)

Nested spans inherit the outer element's text styling and may override color, background_color, font_size, font_family, font_weight, bold, italic, text_decoration, and letter_spacing. On the wire each pressable span carries pressable: True; native reports on_span_press(index) and Python routes it to that span's callback.

Parameters:

Name Type Description Default
*parts Any

Text content: a single string, or any mix of strings and nested Text elements for rich text.

()
on_press Optional[Callable[[], Any]]

Callback invoked when the whole label is tapped (or, on a nested Text, when that span is tapped).

None
ellipsize_mode EllipsizeMode

Where to truncate when the text exceeds max_lines: "head", "middle", "tail" (default), or "clip" (no ellipsis). Android draws "head" and "middle" only on single-line text.

'tail'
selectable bool

Let the user select and copy the text.

False
allow_font_scaling bool

Scale the font with the user's accessibility text size (iOS Dynamic Type, Android sp). Set False for text that must keep its exact size.

True
style StyleProp

Style dict (or list of dicts).

None
ref Optional[Ref]

Optional Ref from use_ref().

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "Text".

TextInput

TextInput(
    *,
    value: str = "",
    placeholder: Optional[str] = None,
    on_change: Optional[Callable[[str], Any]] = None,
    on_selection_change: Optional[
        Callable[[SelectionEvent], Any]
    ] = None,
    on_submit: Optional[Callable[[str], Any]] = None,
    on_key_press: Optional[
        Callable[[KeyPressEvent], Any]
    ] = None,
    on_content_size_change: Optional[
        Callable[[ContentSizeEvent], Any]
    ] = None,
    selection: Optional[Tuple[int, int]] = None,
    secure: bool = False,
    multiline: bool = False,
    keyboard_type: Optional[KeyboardType] = None,
    keyboard_appearance: KeyboardAppearance = "default",
    auto_capitalize: Optional[AutoCapitalize] = None,
    auto_correct: Optional[bool] = None,
    auto_focus: bool = False,
    select_text_on_focus: bool = False,
    blur_on_submit: Optional[bool] = None,
    return_key_type: Optional[ReturnKeyType] = None,
    max_length: Optional[int] = None,
    placeholder_color: Optional[Color] = None,
    editable: bool = True,
    clear_button: bool = False,
    on_focus: Optional[Callable[[], Any]] = None,
    on_blur: Optional[Callable[[], Any]] = None,
    selection_color: Optional[Color] = None,
    text_content_type: Optional[str] = None,
    style: StyleProp = None,
    ref: Optional[Ref] = None,
    key: Optional[str] = None,
    **props: Unpack[AccessibilityProps]
) -> Element

Display a text-entry field (single-line by default, or multiline).

Style properties: font_size, color, background_color, border_*, plus the common layout props.

pn.TextInput(
    value=text, on_change=set_text,
    selection=(start, end), on_selection_change=lambda e: ...,
    on_key_press=lambda e: ...,
    select_text_on_focus=True,
    keyboard_appearance="dark",
    ref=input_ref,
)

Parameters:

Name Type Description Default
value str

Current text content (controlled-input pattern).

''
placeholder Optional[str]

Hint shown when value is empty.

None
on_change Optional[Callable[[str], Any]]

Callback invoked with the new string each keystroke.

None
on_selection_change Optional[Callable[[SelectionEvent], Any]]

Callback invoked with a SelectionEvent (UTF-16 offsets) when the caret or selection moves.

None
on_submit Optional[Callable[[str], Any]]

Callback invoked when the user submits (Return / Done / etc.). Receives the final text.

None
on_key_press Optional[Callable[[KeyPressEvent], Any]]

Callback invoked with a KeyPressEvent per key: the typed character, or "Backspace" / "Enter". iOS and Android report only what their input pipeline exposes (characters, backspace, and the return key); the browser reports every key.

None
on_content_size_change Optional[Callable[[ContentSizeEvent], Any]]

Callback invoked with a ContentSizeEvent when the text's measured size changes (auto-growing multiline fields).

None
selection Optional[Tuple[int, int]]

Controlled selection as (start, end) UTF-16 offsets; start == end places the caret.

None
secure bool

When True, characters are masked (use for passwords).

False
multiline bool

When True, allows multiple lines of input.

False
keyboard_type Optional[KeyboardType]

One of the KeyboardType values, e.g. "email_address", "number_pad", "numbers_and_punctuation", "visible_password".

None
keyboard_appearance KeyboardAppearance

iOS keyboard theme: "default", "light", or "dark". Ignored elsewhere.

'default'
auto_capitalize Optional[AutoCapitalize]

One of "none", "sentences", "words", "characters".

None
auto_correct Optional[bool]

Enable/disable autocorrection.

None
auto_focus bool

Request focus on mount.

False
select_text_on_focus bool

Select the whole text when the field gains focus.

False
blur_on_submit Optional[bool]

Whether submitting blurs the field. None (default) blurs single-line fields and keeps multiline fields focused, as React Native does.

None
return_key_type Optional[ReturnKeyType]

One of "default", "done", "go", "next", "send", "search".

None
max_length Optional[int]

Maximum number of characters allowed.

None
placeholder_color Optional[Color]

Color used for the placeholder string.

None
editable bool

When False, the field is read-only (still selectable).

True
clear_button bool

When True, shows a clear ("x") button while editing (iOS clearButtonMode; an inline button on Android).

False
on_focus Optional[Callable[[], Any]]

Callback invoked when the field gains focus.

None
on_blur Optional[Callable[[], Any]]

Callback invoked when the field loses focus.

None
selection_color Optional[Color]

Cursor / selection highlight color.

None
text_content_type Optional[str]

Semantic content hint for autofill (e.g. "username", "password", "one_time_code").

None
style StyleProp

Style dict (or list of dicts).

None
ref Optional[Ref]

Optional Ref from use_ref(); receives a TextInputHandle with focus(), blur(), clear(), and friends.

None
key Optional[str]

Stable identity for keyed reconciliation.

None
**props Unpack[AccessibilityProps]

Shared accessibility and test keywords; see AccessibilityProps.

{}

Returns:

Type Description
Element

An Element of type "TextInput".

Shared props

Every built-in view accepts the AccessibilityProps keywords, and View, Column, Row, and Pressable also accept the ViewProps layout and gesture keywords. Factories declare them as **props: Unpack[...], so a type checker validates each keyword as if it were spelled out in the signature. Built-in props are validated at run time only in development builds.

Props shared by the built-in components, declared once as TypedDicts.

Every built-in view accepts the AccessibilityProps keywords, and the plain containers and Pressable also accept the ViewProps layout and gesture keywords. Factories declare them as **props: Unpack[...], so a type checker validates each keyword exactly as if it were spelled out in the signature, and the reference documentation describes each one here instead of in every factory.

pn.View(
    pn.Text("Delete"),
    accessibility_label="Delete message",
    accessibility_role="button",
    test_id="delete",
    on_layout=lambda event: print(event.width),
)

Classes:

Name Description
AccessibilityProps

Assistive-technology and UI-test keywords accepted by every built-in view.

ViewProps

Layout and gesture keywords accepted by View, Column, Row, and Pressable.

AccessibilityProps

Bases: TypedDict

Assistive-technology and UI-test keywords accepted by every built-in view.

Attributes:

Name Type Description
accessibility_label str | None

Spoken description for screen readers.

accessibility_hint str | None

Spoken extra detail about the result of acting on the view (appended to the content description on Android).

accessibility_role str | None

Semantic role ("button", "header", "link", "image", ...). Controls with a fixed role (Checkbox, Switch) supply their own.

accessible bool | None

Override whether the view is exposed to assistive technology as a single element.

accessibility_state AccessibilityState | None

Current widget state, an AccessibilityState.

accessibility_value Union[str, AccessibilityValue, None]

Current value: a string, or an AccessibilityValue with min / max / now / text.

accessibility_actions Sequence[AccessibilityAction] | None

Custom actions a screen reader may invoke, each an AccessibilityAction.

on_accessibility_action Callable[[str], Any] | None

Called with the action name when a screen reader triggers one of accessibility_actions.

accessibility_live_region Literal['none', 'polite', 'assertive'] | None

How assistive technology announces changes to this view: "none", "polite", or "assertive".

important_for_accessibility ImportantForAccessibility | None

Whether assistive technology sees this view and its subtree: "auto", "yes", "no", or "no_hide_descendants".

test_id str | None

Stable identifier for UI tests, exposed as accessibilityIdentifier on iOS and resource-id on Android.

ViewProps

Bases: AccessibilityProps

Layout and gesture keywords accepted by View, Column, Row, and Pressable.

Includes every AccessibilityProps key.

Attributes:

Name Type Description
gestures List[Any] | None

Gesture descriptors from pythonnative.gestures recognized natively on this view.

hit_slop Union[float, Dict[str, float], None]

Extra touch target beyond the view's bounds: one number for every edge, or a dict with top / right / bottom / left.

on_layout Callable[[LayoutEvent], Any] | None

Called with a LayoutEvent after layout and whenever the view's frame changes.

List data and records

ListData publishes explicit keyed edits to FlatList. Section gives each section a stable identity, and ViewableItem describes a visible item. See the list guide for ownership, batching, and performance details.

Typed, keyed list data with explicit mutations and bounded change history.

Classes:

Name Description
ListData

A keyed collection that publishes explicit edits to virtualized lists.

Section

A section whose identity survives insertion, removal, and reordering.

ViewableItem

An item currently visible in the native viewport.

ListData

ListData(
    items: Iterable[T] = (),
    *,
    key: Callable[[T], str],
    history_limit: int = 1024
)

Bases: Sequence[T]

A keyed collection that publishes explicit edits to virtualized lists.

The first thread that subscribes to or mutates the collection owns it, normally the application thread; later subscriptions and mutations must happen there. Creating one at module import time (a module-level repository, say) is fine even when the import runs on another thread. Items are application values: replace an item with update after editing it instead of mutating it silently. Keys must be unique, nonempty strings and can't change in an update.

update and key lookup take constant time. Insertion, removal, and moves shift an indexed Python list, but don't re-render or serialize unaffected items. batch coalesces notifications; it isn't a rollback transaction. Successful edits remain applied if the body raises. A bounded journal lets multiple mounted lists catch up independently; a lagging list receives a fresh snapshot after its history has expired.

Methods:

Name Description
get

Return an item by its stable key, raising KeyError if absent.

subscribe

Subscribe to changes and return an idempotent unsubscribe function.

batch

Coalesce subscriber notifications, including nested batches.

insert

Insert an item at an index between zero and len(self).

append

Append a new keyed item.

update

Replace an item while preserving its key and mounted component state.

remove

Remove and return the item with key.

move

Move an item to its final zero-based index, preserving its identity.

clear

Remove every item with one snapshot invalidation.

Attributes:

Name Type Description
revision int

Monotonically increasing mutation version for subscriptions.

revision property

revision: int

Monotonically increasing mutation version for subscriptions.

get

get(key: str) -> T

Return an item by its stable key, raising KeyError if absent.

subscribe

subscribe(
    callback: Callable[[], None],
) -> Callable[[], None]

Subscribe to changes and return an idempotent unsubscribe function.

batch

batch() -> Iterator[ListData[T]]

Coalesce subscriber notifications, including nested batches.

insert

insert(index: int, item: T) -> None

Insert an item at an index between zero and len(self).

append

append(item: T) -> None

Append a new keyed item.

update

update(key: str, item: T) -> None

Replace an item while preserving its key and mounted component state.

remove

remove(key: str) -> T

Remove and return the item with key.

move

move(key: str, index: int) -> None

Move an item to its final zero-based index, preserving its identity.

clear

clear() -> None

Remove every item with one snapshot invalidation.

Section dataclass

Section(key: str, data: Sequence[T], title: str = '')

Bases: Generic[T]

A section whose identity survives insertion, removal, and reordering.

ViewableItem dataclass

ViewableItem(key: str, index: int, item: T)

Bases: Generic[T]

An item currently visible in the native viewport.

Typed event payloads

Frozen dataclasses delivered to on_layout, on_scroll (and the drag and momentum callbacks), on_selection_change, on_key_press, on_content_size_change, on_load, and the WebView navigation callbacks. Field names match the wire payload, which is what lets Animated.event bind by name (Animated.event(y=scroll_y)).

Typed event payloads delivered by the built-in components.

Every record here is a frozen, slotted dataclass, so callbacks read event.y instead of payload["y"] and a misspelled field is an AttributeError rather than a silent None. The wire payload for each event is a JSON object whose keys match the field names, which is what lets Animated.event(on_scroll, y=scroll_y) keep binding by name: the contract generator derives the native record from these classes and the bridge reconstructs them before the callback runs.

Classes:

Name Description
LayoutEvent

A view's committed frame, in the parent's coordinate space and logical units.

ScrollEvent

A scroll container's offset and geometry at the moment of the event.

SelectionEvent

A text field's selection as UTF-16 offsets (start == end is a caret).

KeyPressEvent

One key press inside a text field.

ContentSizeEvent

The measured size of a text field's content, in logical units.

ImageLoadEvent

Decoded image dimensions in the platform's logical display units.

WebNavigationEvent

The top-level document's navigation state at a load transition.

LayoutEvent dataclass

LayoutEvent(
    x: float, y: float, width: float, height: float
)

A view's committed frame, in the parent's coordinate space and logical units.

Delivered to on_layout after the first layout and again whenever the frame changes.

ScrollEvent dataclass

ScrollEvent(
    x: float,
    y: float,
    content_width: float = 0.0,
    content_height: float = 0.0,
    viewport_width: float = 0.0,
    viewport_height: float = 0.0,
)

A scroll container's offset and geometry at the moment of the event.

Delivered to on_scroll and the drag and momentum callbacks of ScrollView, and to on_scroll on FlatList and SectionList. Geometry fields default to 0.0 when a renderer reports only the offset.

SelectionEvent dataclass

SelectionEvent(start: int, end: int)

A text field's selection as UTF-16 offsets (start == end is a caret).

KeyPressEvent dataclass

KeyPressEvent(key: str)

One key press inside a text field.

key is the typed character, or "Backspace" / "Enter" for those keys. Native platforms report only what their input pipeline exposes: iOS and Android see characters, backspace, and the return key; the browser reports every key.

ContentSizeEvent dataclass

ContentSizeEvent(width: float, height: float)

The measured size of a text field's content, in logical units.

ImageLoadEvent dataclass

ImageLoadEvent(width: float, height: float)

Decoded image dimensions in the platform's logical display units.

WebNavigationEvent dataclass

WebNavigationEvent(
    url: str,
    loading: bool,
    can_go_back: bool,
    can_go_forward: bool,
    title: str = "",
)

The top-level document's navigation state at a load transition.

Next steps