Style¶
PythonNative styles are plain Python dicts typed by the
Style TypedDict. An element's style prop
may be a single dict, a list of dicts (later entries win on key
collision, and None entries are skipped), or None.
StyleSheet is a namespace base class for
named styles with typed attribute access, and
ABSOLUTE_FILL is the common
full-parent overlay. Theme tokens and theme-dependent styles live in
Theme.
The typed Style, style resolution, and style sheets.
PythonNative ships a single, fully typed Style
TypedDict that enumerates every supported style property and
constrains enum-shaped values with typing.Literal.
Editors and type checkers (mypy, pyright) autocomplete and validate
every key: flex_direction="collumn" is a static error, not a silent
runtime no-op.
Style values are plain dicts at runtime, so they're trivial to compose,
diff, and store. Pass one dict or a list of them (later entries win,
None entries are skipped); resolve_style
flattens the list and resolves the inset* shorthands.
Group related styles in a StyleSheet
namespace, and derive theme-dependent styles with
use_styles:
import pythonnative as pn
class Styles(pn.StyleSheet):
container = pn.style(padding=16, gap=12)
title = pn.style(font_size=24, font_weight="700")
pn.Column(pn.Text("Hello", style=Styles.title), style=Styles.container)
Classes:
| Name | Description |
|---|---|
DynamicColor |
A color pair resolved against the current color scheme. |
EdgeInsets |
Per-edge spacing values used for |
AccessibilityState |
Current widget state exposed to assistive technology. |
AccessibilityValue |
The current value of a range-like or text-valued widget, for assistive technology. |
AccessibilityAction |
One custom action a screen reader may invoke on a view. |
ShadowOffset |
Shadow displacement in points. |
TransformRotate |
Rotation around the z axis in degrees (numeric) or with an explicit unit suffix. |
TransformRotateX |
Rotation around the x axis (a 3D tilt) in degrees or with a unit suffix. |
TransformRotateY |
Rotation around the y axis (a 3D flip) in degrees or with a unit suffix. |
TransformRotateZ |
Rotation around the z axis; an explicit spelling of |
TransformScale |
Uniform scale transform. |
TransformScaleX |
Horizontal-only scale transform. |
TransformScaleY |
Vertical-only scale transform. |
TransformTranslate |
Translation transform along one or both axes. |
TransformSkewX |
Horizontal skew in degrees or with a unit suffix. |
TransformSkewY |
Vertical skew in degrees or with a unit suffix. |
TransformPerspective |
Perspective distance for the 3D rotations that follow it in the list. |
Style |
Statically-typed style dictionary. |
StyleSheet |
Base class for a namespace of named styles. |
Functions:
| Name | Description |
|---|---|
style |
Construct a |
resolve_style |
Flatten a |
validate_style_keys |
Warn (once per key) about style keys no built-in handler reads. |
Attributes:
| Name | Type | Description |
|---|---|---|
Color |
Color value: |
|
Dimension |
A length value. Numbers are points/dp; strings ending in |
|
EdgeValue |
Padding/margin value: a uniform number, a |
|
ImportantForAccessibility |
|
|
ShadowOffsetValue |
|
|
TransformEntry |
A single transform operation. Every renderer supports the whole set; |
|
TransformSpec |
|
|
Display |
|
|
TextTransform |
|
|
MarginValue |
A margin length: points, a |
|
BorderStyle |
|
|
KeyboardType |
|
|
PointerEvents |
Touch-handling mode for a view and its subtree: |
|
StyleProp |
Public type for the |
|
ABSOLUTE_FILL |
Style
|
A style that absolutely fills the parent, like React Native's |
LAYOUT_STYLE_KEYS
module-attribute
¶
LAYOUT_STYLE_KEYS = frozenset(
{
"width",
"height",
"min_width",
"max_width",
"min_height",
"max_height",
"flex",
"flex_grow",
"flex_shrink",
"flex_basis",
"flex_wrap",
"align_self",
"align_content",
"position",
"top",
"right",
"bottom",
"left",
"start",
"end",
"margin",
"margin_top",
"margin_bottom",
"margin_left",
"margin_right",
"margin_start",
"margin_end",
"margin_horizontal",
"margin_vertical",
"padding",
"padding_top",
"padding_bottom",
"padding_left",
"padding_right",
"padding_start",
"padding_end",
"padding_horizontal",
"padding_vertical",
"border_width",
"border_top_width",
"border_right_width",
"border_bottom_width",
"border_left_width",
"flex_direction",
"justify_content",
"align_items",
"gap",
"row_gap",
"column_gap",
"aspect_ratio",
"direction",
"display",
}
)
Style keys that affect layout (the renderer core hands them to Yoga).
Color
module-attribute
¶
Color = Union[str, DynamicColor]
Color value: "#RRGGBB", "#AARRGGBB", any string a platform
handler recognizes (e.g., "red"), or a
DynamicColor {"light": ..., "dark": ...}
pair. Strings are stored verbatim and parsed by the handler at apply-time,
so palettes from third-party libraries pass through unchanged.
Dimension
module-attribute
¶
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.
ImportantForAccessibility
module-attribute
¶
ImportantForAccessibility = Literal[
"auto", "yes", "no", "no_hide_descendants"
]
important_for_accessibility value: whether assistive technology
sees the view ("yes"), skips it ("no"), skips it and its subtree
("no_hide_descendants"), or decides itself ("auto").
ShadowOffsetValue
module-attribute
¶
shadow_offset / text_shadow_offset value: an
ShadowOffset dict or an (x, y) pair.
TransformEntry
module-attribute
¶
TransformEntry = Union[
TransformRotate,
TransformRotateX,
TransformRotateY,
TransformRotateZ,
TransformScale,
TransformScaleX,
TransformScaleY,
TransformTranslate,
TransformSkewX,
TransformSkewY,
TransformPerspective,
Dict[str, Any],
]
A single transform operation. Every renderer supports the whole set;
iOS composes them into a CATransform3D.
TransformSpec
module-attribute
¶
TransformSpec = Union[TransformEntry, List[TransformEntry]]
transform style value: a single operation or an ordered list.
Display
module-attribute
¶
Display = Literal['flex', 'none']
display style value. "none" removes the node and its subtree
from layout entirely (no size, gap, or margin contribution; every frame
in the subtree is (0, 0, 0, 0)).
TextTransform
module-attribute
¶
TextTransform = Literal[
"none", "uppercase", "lowercase", "capitalize"
]
text_transform style value. Applied in Python before the string
reaches the native label, so measurement and rendering agree.
MarginValue
module-attribute
¶
A margin length: points, a "%" string, or "auto" to absorb free space.
BorderStyle
module-attribute
¶
BorderStyle = Literal['solid', 'dashed', 'dotted']
border_style style value, drawn the same way on every renderer.
KeyboardType
module-attribute
¶
KeyboardType = Literal[
"default",
"email_address",
"number_pad",
"decimal_pad",
"phone_pad",
"url",
"ascii",
"numbers_and_punctuation",
"web_search",
"visible_password",
]
keyboard_type value. "ascii", "numbers_and_punctuation",
and "web_search" are iOS keyboards (Android and the browser fall back
to the closest input type); "visible_password" is Android's
unmasked password keyboard.
PointerEvents
module-attribute
¶
PointerEvents = Literal[
"auto", "none", "box_none", "box_only"
]
Touch-handling mode for a view and its subtree:
"auto": the view and its children receive touches (default)."none": neither the view nor its children receive touches; touches pass through to whatever is underneath."box_none": the view itself ignores touches but its children still receive them (decorative overlays with interactive content)."box_only": the view receives touches but its children do not.
StyleProp
module-attribute
¶
Public type for the style parameter on every component factory.
Accepts a Style TypedDict, a sequence of them
with None entries skipped, or None. Style is a TypedDict,
so a plain dict literal type-checks against it and still works at
runtime.
ABSOLUTE_FILL
module-attribute
¶
ABSOLUTE_FILL: Style = {
"position": "absolute",
"top": 0,
"right": 0,
"bottom": 0,
"left": 0,
}
A style that absolutely fills the parent, like React Native's StyleSheet.absoluteFill.
DynamicColor
¶
Bases: TypedDict
A color pair resolved against the current color scheme.
Every renderer (iOS, Android, and the browser preview) picks
light or dark when the style is applied and switches when
the appearance changes.
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. |
busy |
bool
|
The widget is loading or otherwise temporarily busy. |
expanded |
bool
|
A disclosure/accordion is currently expanded. |
AccessibilityValue
¶
Bases: TypedDict
The current value of a range-like or text-valued widget, for assistive technology.
Passed via accessibility_value= (a plain string is also
accepted and equivalent to {"text": ...}). Use min, max,
and now for sliders and progress indicators, text for
everything else.
Attributes:
| Name | Type | Description |
|---|---|---|
min |
float
|
Lower bound of the range. |
max |
float
|
Upper bound of the range. |
now |
float
|
Current value within the range. |
text |
str
|
Spoken description of the current value. |
AccessibilityAction
¶
Bases: TypedDict
One custom action a screen reader may invoke on a view.
Passed via accessibility_actions=[...]; the view's
on_accessibility_action callback receives the action name.
The standard names "activate", "increment", "decrement",
"longpress", "magicTap", and "escape" map to the
platform's built-in actions; any other name is a custom action
announced with label.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Identifier reported to |
label |
NotRequired[str]
|
Spoken description of a custom action. |
TransformRotate
¶
TransformRotateX
¶
TransformRotateY
¶
TransformPerspective
¶
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
StyleSheet
¶
Base class for a namespace of named styles.
Subclass it and assign Style dicts as class
attributes. Attribute access is typed, so a misspelled style name is
a static error, and every style is checked for unknown keys once in
dev mode:
class Styles(pn.StyleSheet):
card = pn.style(padding=16, border_radius=12)
title = pn.style(font_size=17, font_weight="600")
pn.View(pn.Text("Hello", style=Styles.title), style=Styles.card)
Compose styles with a list (style=[Styles.card, {"opacity": 0.5}]).
For styles derived from the theme, see
use_styles. A style sheet is a
namespace, not an object: instantiating one raises TypeError.
style
¶
Construct a Style from keyword arguments.
Equivalent to Style(...) but reads more naturally inside
expressions, and typed with Unpack[Style] so a type checker
rejects a misspelled key such as pn.style(colour="red"):
At runtime the keys aren't checked here; the factories warn once
per unknown key in dev mode through
validate_style_keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**properties
|
Unpack[Style]
|
Style key/value pairs. |
{}
|
Returns:
| Type | Description |
|---|---|
Style
|
A fresh |
resolve_style
¶
Flatten a style prop into a single dict.
Accepts None, a single dict, or a sequence of dicts (later
entries override earlier ones, mirroring React Native's array-style
pattern), then resolves the inset, inset_horizontal, and
inset_vertical shorthands into top / right / bottom
/ left. Used by every built-in element factory in
pythonnative.components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
StyleProp
|
The raw value of the component's |
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
¶
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).
A small set of enum-shaped keys (display, position,
direction, text_decoration, text_transform,
pointer_events, border_style) and the text_shadow_* keys also have their
values checked; a bad value warns once per key/value pair and is
otherwise passed through (the engine and handlers ignore values
they don't recognize).
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.
|
''
|
Next steps¶
- See worked examples in Styling.
- Use design tokens and dark mode with Theme.
- See the full per-component property catalogue in Component properties.