0
# ReactPy
1
2
ReactPy is a library for building user interfaces in Python without JavaScript. It provides a component-based architecture with React-style hooks and declarative UI patterns, enabling Python developers to create interactive web applications using familiar React concepts while staying entirely within the Python ecosystem.
3
4
## Package Information
5
6
- **Package Name**: reactpy
7
- **Language**: Python
8
- **Installation**: `pip install reactpy`
9
10
## Core Imports
11
12
```python
13
import reactpy
14
```
15
16
Common patterns for building components:
17
18
```python
19
from reactpy import component, html, use_state
20
```
21
22
For working with backends:
23
24
```python
25
from reactpy import run
26
from reactpy.backend import fastapi, flask, starlette # etc.
27
```
28
29
## Basic Usage
30
31
```python
32
from reactpy import component, html, use_state, run
33
34
@component
35
def Counter():
36
count, set_count = use_state(0)
37
38
def increment():
39
set_count(count + 1)
40
41
return html.div(
42
html.h1(f"Count: {count}"),
43
html.button(
44
{"onClick": increment},
45
"Increment"
46
)
47
)
48
49
# Run the application
50
run(Counter)
51
```
52
53
More complex example with effects:
54
55
```python
56
from reactpy import component, html, use_state, use_effect
57
58
@component
59
def Timer():
60
seconds, set_seconds = use_state(0)
61
62
def tick():
63
set_seconds(seconds + 1)
64
65
use_effect(
66
lambda: set_interval(tick, 1000),
67
[] # Run once on mount
68
)
69
70
return html.div(
71
html.h2(f"Timer: {seconds} seconds"),
72
html.p("This timer updates every second")
73
)
74
```
75
76
## Architecture
77
78
ReactPy follows a component-based architecture inspired by React:
79
80
- **Components**: Decorated functions that return VDOM elements, managing their own state and lifecycle
81
- **Hooks**: Functions like `use_state`, `use_effect` that enable state management and side effects
82
- **VDOM**: Virtual DOM representation for efficient rendering and updates
83
- **Layouts**: Rendering system that manages component trees and updates
84
- **Backends**: Integration layer supporting multiple web frameworks (FastAPI, Flask, etc.)
85
86
This design enables reactive interfaces where UI automatically updates when state changes, while providing the flexibility to integrate with various Python web frameworks and deployment scenarios.
87
88
## Capabilities
89
90
### Components and Decorators
91
92
Core functionality for defining ReactPy components with proper lifecycle management and rendering.
93
94
```python { .api }
95
@component
96
def my_component(*args, **kwargs) -> VdomDict: ...
97
98
class Component:
99
def __init__(self, function, key, args, kwargs, sig): ...
100
key: Any
101
type: Callable
102
```
103
104
[Components](./components.md)
105
106
### Hooks and State Management
107
108
React-style hooks for managing component state, side effects, and context in functional components.
109
110
```python { .api }
111
def use_state(initial_value: T | Callable[[], T]) -> tuple[T, Callable[[T], None]]: ...
112
def use_effect(function: Callable[[], None | Callable[[], None]], dependencies: list[Any] | None = None) -> None: ...
113
def use_callback(function: Callable[..., Any], dependencies: list[Any] | None = None) -> Callable[..., Any]: ...
114
def use_memo(function: Callable[[], Any], dependencies: list[Any] | None = None) -> Any: ...
115
def use_ref(initial_value: T = None) -> Ref[T]: ...
116
def use_context(context: Context[T]) -> T: ...
117
def use_reducer(reducer: Callable[[S, A], S], initial_state: S) -> tuple[S, Callable[[A], None]]: ...
118
def use_debug_value(value: Any, formatter: Callable[[Any], str] | None = None) -> None: ...
119
def use_scope() -> MutableMapping[str, Any]: ...
120
def use_location() -> Location: ...
121
def use_connection() -> Connection[Any]: ...
122
def create_context(default_value: T) -> Context[T]: ...
123
```
124
125
[Hooks](./hooks.md)
126
127
### HTML Elements
128
129
Complete set of HTML element constructors for building user interfaces declaratively.
130
131
```python { .api }
132
def div(*children, **attributes) -> VdomDict: ...
133
def h1(*children, **attributes) -> VdomDict: ...
134
def p(*children, **attributes) -> VdomDict: ...
135
def button(*children, **attributes) -> VdomDict: ...
136
def input(**attributes) -> VdomDict: ...
137
def form(*children, **attributes) -> VdomDict: ...
138
# ... 102 total HTML elements
139
```
140
141
[HTML Elements](./html-elements.md)
142
143
### SVG Elements
144
145
SVG element constructors for creating scalable vector graphics and data visualizations.
146
147
```python { .api }
148
def svg(*children, **attributes) -> VdomDict: ...
149
def circle(**attributes) -> VdomDict: ...
150
def rect(**attributes) -> VdomDict: ...
151
def path(**attributes) -> VdomDict: ...
152
def g(*children, **attributes) -> VdomDict: ...
153
# ... 69 total SVG elements
154
```
155
156
[SVG Elements](./svg-elements.md)
157
158
### Event Handling
159
160
Event system for handling user interactions with proper event delegation and prevention.
161
162
```python { .api }
163
def event(
164
function: Callable[..., Any] | None = None,
165
*,
166
stop_propagation: bool = False,
167
prevent_default: bool = False,
168
) -> EventHandler | Callable[[Callable[..., Any]], EventHandler]: ...
169
170
class EventHandler:
171
function: EventHandlerFunc
172
prevent_default: bool
173
stop_propagation: bool
174
target: str | None
175
176
def __init__(
177
self,
178
function: EventHandlerFunc,
179
stop_propagation: bool = False,
180
prevent_default: bool = False,
181
target: str | None = None,
182
) -> None: ...
183
```
184
185
[Events](./events.md)
186
187
### Backend Integration
188
189
Support for multiple web frameworks enabling deployment across different Python web environments.
190
191
```python { .api }
192
def run(
193
component: RootComponentConstructor,
194
host: str = "127.0.0.1",
195
port: int | None = None,
196
implementation: BackendType[Any] | None = None,
197
) -> None: ...
198
199
# Backend-specific functions
200
# From reactpy.backend.fastapi
201
def configure(app: FastAPI, component: RootComponentConstructor, options: Options | None = None) -> None: ...
202
203
# From reactpy.backend.flask
204
def configure(app: Flask, component: RootComponentConstructor, options: Options | None = None) -> None: ...
205
206
# From reactpy.backend.starlette
207
def configure(app: Starlette, component: RootComponentConstructor, options: Options | None = None) -> None: ...
208
209
# From reactpy.backend.sanic
210
def configure(app: Sanic[Any, Any], component: RootComponentConstructor, options: Options | None = None) -> None: ...
211
212
# From reactpy.backend.tornado
213
def configure(app: Application, component: RootComponentConstructor, options: Options | None = None) -> None: ...
214
```
215
216
[Backend Integration](./backend.md)
217
218
### VDOM and Rendering
219
220
Virtual DOM system for efficient component rendering and layout management.
221
222
```python { .api }
223
def vdom(tag: str, *children, **attributes) -> VdomDict: ...
224
def html_to_vdom(html_string: str) -> VdomDict: ...
225
def vdom_to_html(vdom_dict: VdomDict) -> str: ...
226
227
class Layout:
228
def __init__(self, component: ComponentType): ...
229
async def render() -> LayoutUpdate: ...
230
async def deliver(event: LayoutEvent) -> None: ...
231
```
232
233
[VDOM and Rendering](./vdom.md)
234
235
### Web Modules
236
237
JavaScript module integration system for incorporating client-side functionality.
238
239
```python { .api }
240
def module_from_template(name: str, template: str, **params) -> WebModule: ...
241
def module_from_file(name: str, file: str | Path) -> WebModule: ...
242
def module_from_url(name: str, url: str, dev: bool = False) -> WebModule: ...
243
244
# Overloaded export function
245
def export(
246
web_module: WebModule,
247
export_names: str,
248
fallback: Any | None = None,
249
allow_children: bool = True,
250
) -> VdomDictConstructor: ...
251
252
def export(
253
web_module: WebModule,
254
export_names: list[str] | tuple[str, ...],
255
fallback: Any | None = None,
256
allow_children: bool = True,
257
) -> list[VdomDictConstructor]: ...
258
```
259
260
[Web Modules](./web-modules.md)
261
262
### Widgets and Utilities
263
264
Pre-built components and utility functions for common use cases and data manipulation.
265
266
```python { .api }
267
def image(src: str, **attributes) -> VdomDict: ...
268
def linked_inputs(*inputs) -> list[VdomDict]: ...
269
270
class Ref[T]:
271
current: T
272
def __init__(self, initial_value: T = None): ...
273
274
def SampleApp() -> VdomDict: ...
275
```
276
277
[Widgets and Utilities](./widgets.md)
278
279
### Testing Support
280
281
Comprehensive testing framework with fixtures and utilities for component testing.
282
283
```python { .api }
284
class BackendFixture:
285
def __init__(self, implementation): ...
286
async def mount(self, component: ComponentType) -> None: ...
287
288
class DisplayFixture:
289
def __init__(self, backend_fixture): ...
290
def goto(self, path: str) -> None: ...
291
async def mount(self, component: ComponentType) -> None: ...
292
page: Page # Playwright page object
293
294
def poll(coroutine: Callable, timeout: float = None) -> Any: ...
295
```
296
297
[Testing](./testing.md)
298
299
### Configuration
300
301
Configuration options and environment variables for customizing ReactPy behavior.
302
303
```python { .api }
304
# Configuration variables (set via environment)
305
REACTPY_DEBUG_MODE: bool
306
REACTPY_BACKEND_HOST: str
307
REACTPY_BACKEND_PORT: int
308
REACTPY_WEB_MODULES_DIR: str
309
REACTPY_ASYNC_RENDERING: bool
310
```
311
312
[Configuration](./configuration.md)
313
314
## Types
315
316
Core type definitions used throughout ReactPy:
317
318
```python { .api }
319
# Component Types
320
ComponentType = Protocol
321
ComponentConstructor = Callable[..., ComponentType]
322
RootComponentConstructor = Callable[[], ComponentType]
323
324
# State Management
325
State[T] = NamedTuple # (value: T, set_value: Callable[[T], None])
326
Context[T] = TypeVar("Context")
327
328
# VDOM Types
329
VdomDict = dict[str, Any]
330
VdomChild = ComponentType | VdomDict | str | None
331
VdomChildren = Sequence[VdomChild]
332
VdomAttributes = dict[str, Any]
333
334
# Event Handling
335
EventHandlerFunc = Callable[..., Any]
336
EventHandlerType = EventHandler | EventHandlerFunc
337
EventHandlerMapping = dict[str, EventHandlerType]
338
339
# Utility Types
340
Key = str | int
341
Location = NamedTuple # Backend-specific location info
342
Connection[T] = TypeVar("Connection") # Backend-specific connection
343
BackendType[T] = Protocol # Backend implementation interface
344
345
# Layout and Rendering
346
LayoutType = Protocol # Manages component trees and updates
347
348
# Web Modules
349
WebModule = Any # JavaScript module integration
350
VdomDictConstructor = Callable[..., VdomDict]
351
```