Skip to content

Style

PythonNative styles are plain Python dicts; an element's style prop may be a single dict or a list of dicts (later entries win on key collision). StyleSheet is a small helper for declaring named styles and composing them.

StyleSheet, typed Style, style resolution, and theming.

PythonNative ships a single, fully-typed Style TypedDict that enumerates every supported style property and constrains enum-shaped values via typing.Literal. The TypedDict gives editors and type-checkers (mypy, pyright) full autocomplete and validation: a typo such as flex_direction="collumn" is now a static error, not a silent runtime no-op.

Style values remain plain dicts at runtime so they are trivial to compose, diff, and store. Properties unrecognized by a platform handler are still ignored, so third-party handlers may extend the palette without modifying core types.

The runtime helpers (resolve_style, StyleSheet) accept either a Style TypedDict, a regular Dict[str, Any] (for forward-compat or unrestricted use), or a list of either kind of dict, and always return a fresh, flat dict.

Example
import pythonnative as pn

styles = pn.StyleSheet.create(
    title=pn.style(font_size=24, bold=True, color="#333"),
    container=pn.style(padding=16, spacing=12),
)

pn.Column(
    pn.Text("Hello", style=styles["title"]),
    style=styles["container"],
)

Classes:

Name Description
EdgeInsets

Per-edge spacing values used for padding and margin.

ShadowOffset

Shadow displacement in points.

TransformRotate

Rotation transform in degrees (numeric) or with explicit unit suffix.

TransformScale

Uniform scale transform.

TransformScaleX

Horizontal-only scale transform.

TransformScaleY

Vertical-only scale transform.

TransformTranslate

Translation transform along one or both axes.

Style

Statically-typed style dictionary.

StyleSheet

Utility for creating, composing, and flattening style dictionaries.

Functions:

Name Description
style

Construct a Style from keyword arguments.

resolve_style

Flatten a style prop into a single dict.

validate_style_keys

Warn (once per key) about style keys no built-in handler reads.

default_theme

Return the built-in theme dict for scheme ("light" / "dark").

use_theme

Return the active theme, following the system appearance by default.

Attributes:

Name Type Description
Color

Color value: "#RRGGBB", "#AARRGGBB", or any string a platform

Dimension

A length value. Numbers are points/dp; strings ending in "%" are

EdgeValue

Padding/margin value: a uniform number, a "%" string, or an

TransformEntry

A single transform operation.

TransformSpec

transform style value: a single operation or an ordered list.

StyleProp

Public type for the style parameter on every component factory.

DEFAULT_LIGHT_THEME Dict[str, Any]

Built-in light theme selected by use_theme.

DEFAULT_DARK_THEME Dict[str, Any]

Built-in dark theme selected by use_theme.

ThemeContext Context

Theme context that follows the system color scheme by default.

Color module-attribute

Color = str

Color value: "#RRGGBB", "#AARRGGBB", or any string a platform handler recognizes (e.g., "red"). Stored verbatim and parsed by the handler at apply-time, so palettes from third-party libraries pass through unchanged.

Dimension module-attribute

Dimension = Union[int, float, str]

A length value. Numbers are points/dp; strings ending in "%" are parent-relative percentages.

EdgeValue module-attribute

EdgeValue = Union[Dimension, EdgeInsets]

Padding/margin value: a uniform number, a "%" string, or an EdgeInsets dict.

TransformEntry module-attribute

A single transform operation.

TransformSpec module-attribute

transform style value: a single operation or an ordered list.

StyleProp module-attribute

StyleProp = Union[Style, Dict[str, Any], List[Optional[Union[Style, Dict[str, Any]]]], None]

Public type for the style parameter on every component factory.

Accepts a Style TypedDict (recommended), a plain Dict[str, Any] (forward-compat / unrestricted), a list of either with None entries skipped, or None.

DEFAULT_LIGHT_THEME module-attribute

DEFAULT_LIGHT_THEME: Dict[str, Any] = {'primary_color': '#007AFF', 'secondary_color': '#5856D6', 'background_color': '#FFFFFF', 'surface_color': '#F2F2F7', 'text_color': '#000000', 'text_secondary_color': '#8E8E93', 'error_color': '#FF3B30', 'success_color': '#34C759', 'warning_color': '#FF9500', 'font_size': 16, 'font_size_small': 13, 'font_size_large': 20, 'font_size_title': 28, 'spacing': 8, 'spacing_large': 16, 'border_radius': 8}

Built-in light theme selected by use_theme.

DEFAULT_DARK_THEME module-attribute

DEFAULT_DARK_THEME: Dict[str, Any] = {'primary_color': '#0A84FF', 'secondary_color': '#5E5CE6', 'background_color': '#000000', 'surface_color': '#1C1C1E', 'text_color': '#FFFFFF', 'text_secondary_color': '#8E8E93', 'error_color': '#FF453A', 'success_color': '#30D158', 'warning_color': '#FF9F0A', 'font_size': 16, 'font_size_small': 13, 'font_size_large': 20, 'font_size_title': 28, 'spacing': 8, 'spacing_large': 16, 'border_radius': 8}

Built-in dark theme selected by use_theme.

ThemeContext module-attribute

ThemeContext: Context = create_context(_FOLLOW_SYSTEM_THEME)

Theme context that follows the system color scheme by default.

Without a provider, use_theme resolves to DEFAULT_LIGHT_THEME or DEFAULT_DARK_THEME based on the current appearance. Wrap a subtree in Provider(ThemeContext, my_theme, ...) to pin an explicit theme for that subtree, then read it inside descendants via use_theme (or use_context(ThemeContext)).

EdgeInsets

Bases: TypedDict

Per-edge spacing values used for padding and margin.

Mirrors React Native's EdgeInsets shape with PythonNative's convenience aliases. Any subset of keys may be supplied.

AccessibilityState

Bases: TypedDict

Current widget state exposed to assistive technology.

Passed via the accessibility_state= prop on interactive components. All keys are optional; omitted keys are treated as unset (not False).

Attributes:

Name Type Description
disabled bool

The widget is visible but not interactive.

selected bool

The widget is currently selected (e.g. the active tab).

checked Union[bool, Literal['mixed']]

Toggle/checkbox state. "mixed" represents a tri-state checkbox.

busy bool

The widget is loading or otherwise temporarily busy.

expanded bool

A disclosure/accordion is currently expanded.

ShadowOffset

Bases: TypedDict

Shadow displacement in points.

TransformRotate

Bases: TypedDict

Rotation transform in degrees (numeric) or with explicit unit suffix.

TransformScale

Bases: TypedDict

Uniform scale transform.

TransformScaleX

Bases: TypedDict

Horizontal-only scale transform.

TransformScaleY

Bases: TypedDict

Vertical-only scale transform.

TransformTranslate

Bases: TypedDict

Translation transform along one or both axes.

Style

Bases: TypedDict

Statically-typed style dictionary.

Lists every style property recognized by the built-in components plus their layout engine, with enum-shaped values constrained via Literal. Style is a total=False TypedDict so any subset of keys is valid at construction time.

Custom native components may accept additional, unlisted keys; they are ignored by the built-in handlers but flow through the reconciler unmodified, so third-party handlers can read them.

Example
import pythonnative as pn

title: pn.Style = {
    "font_size": 24,
    "color": "#0A84FF",
    "text_align": "center",
}

pn.Text("Hello", style=title)

StyleSheet

Utility for creating, composing, and flattening style dictionaries.

All methods are stateless and return fresh dicts, so the values can be reused safely across components.

Methods:

Name Description
create

Create a set of named styles from keyword arguments.

compose

Merge multiple style dicts.

flatten

Flatten a style value or list of styles into a single dict.

absolute_fill

Return a style that absolutely fills the parent.

create staticmethod

create(**named_styles: Style) -> Dict[str, Style]

Create a set of named styles from keyword arguments.

Parameters:

Name Type Description Default
**named_styles Style

Each keyword argument is a style name mapping to a Style dict.

{}

Returns:

Type Description
Dict[str, Style]

A dict mapping each name to a copy of the supplied style,

Dict[str, Style]

so the caller can mutate the result without affecting the

Dict[str, Style]

originals.

Example
from pythonnative import StyleSheet, style

styles = StyleSheet.create(
    heading=style(font_size=28, bold=True),
    body=style(font_size=16),
)

compose staticmethod

compose(*styles: StyleProp) -> Style

Merge multiple style dicts.

Parameters:

Name Type Description Default
*styles StyleProp

Style dicts to merge. Later dicts override keys from earlier ones. Falsy entries (None) are skipped. List entries are flattened in turn.

()

Returns:

Type Description
Style

A new Style dict containing the merged result.

flatten staticmethod

flatten(styles: StyleProp) -> Style

Flatten a style value or list of styles into a single dict.

Equivalent to resolve_style but exposed on StyleSheet for parity with React Native's API and typed as returning a Style.

Parameters:

Name Type Description Default
styles StyleProp

A single dict, a list of dicts, or None.

required

Returns:

Type Description
Style

A flat Style dict combining the inputs.

absolute_fill staticmethod

absolute_fill() -> Style

Return a style that absolutely fills the parent.

Convenience preset matching React Native's StyleSheet.absoluteFill: position: "absolute" with every inset pinned to 0.

style

style(**properties: Any) -> Style

Construct a Style from keyword arguments.

Equivalent to Style(...) but works with any Python version (TypedDict.__init__ is fragile prior to 3.11) and reads more naturally inside expressions:

pn.View(child, style=pn.style(padding=16, background_color="#fff"))

Unknown keys are accepted at runtime to keep the door open for third-party styling extensions; static type checkers will still reject them when this helper's return type is annotated as Style.

Parameters:

Name Type Description Default
**properties Any

Style key/value pairs.

{}

Returns:

Type Description
Style

A fresh Style dict containing the supplied entries.

resolve_style

resolve_style(value: StyleProp) -> Dict[str, Any]

Flatten a style prop into a single dict.

Accepts None, a single dict (Style or untyped), or a list of dicts (later entries override earlier ones, mirroring React Native's array-style pattern). Used by every built-in element factory in pythonnative.components.

Parameters:

Name Type Description Default
value StyleProp

The raw value of the component's style argument.

required

Returns:

Type Description
Dict[str, Any]

A flat dict suitable for the native handler. Always a fresh

Dict[str, Any]

dict, never the input.

validate_style_keys

validate_style_keys(style_dict: Dict[str, Any], owner: str = '') -> None

Warn (once per key) about style keys no built-in handler reads.

Dev-mode only; production skips the scan entirely. Typos get a "did you mean" suggestion via fuzzy matching against the declared Style keys. Unknown keys still flow through to handlers untouched, so custom components that read extra keys keep working (at the cost of one dev warning).

Parameters:

Name Type Description Default
style_dict Dict[str, Any]

The flattened style dict about to be merged into an element's props.

required
owner str

Element type name for the warning message (e.g. "Text").

''

default_theme

default_theme(scheme: str) -> Dict[str, Any]

Return the built-in theme dict for scheme ("light" / "dark").

use_theme

use_theme() -> Dict[str, Any]

Return the active theme, following the system appearance by default.

If an ancestor mounted a Provider(ThemeContext, ...), that theme is returned as-is. Otherwise the built-in light or dark theme is selected from the effective color scheme (via use_color_scheme, so the component re-renders when the system appearance flips).

Returns:

Type Description
Dict[str, Any]

The active theme dict.

Raises:

Type Description
RuntimeError

If called outside a @component function.

Example
import pythonnative as pn

@pn.component
def Card():
    theme = pn.use_theme()
    return pn.View(
        pn.Text("Hello", style=pn.style(color=theme["text_color"])),
        style=pn.style(background_color=theme["surface_color"]),
    )

Next steps