0
# Brython
1
2
Brython (Browser Python) is a Python-to-JavaScript transpiler that enables Python 3 development directly in web browsers. It provides a complete Python 3 runtime environment with full DOM integration, event handling, and access to browser APIs, eliminating the need for server-side Python execution for client-side web application logic.
3
4
## Package Information
5
6
- **Package Name**: brython
7
- **Package Type**: PyPI (Python) and npm (JavaScript)
8
- **Language**: Python (runtime in JavaScript)
9
- **Installation**: `pip install brython`
10
- **Browser CDN**: `https://cdn.jsdelivr.net/npm/brython@3.13.2/brython.min.js`
11
12
## Core Imports
13
14
**Browser-side Python imports:**
15
16
```python
17
from browser import document, window, console, alert
18
from browser.html import DIV, P, A, INPUT, BUTTON
19
```
20
21
**CLI usage:**
22
23
```python
24
import brython
25
# Access via brython-cli command-line tool
26
```
27
28
## Basic Usage
29
30
**HTML Setup:**
31
32
```html
33
<!DOCTYPE html>
34
<html>
35
<head>
36
<script src="https://cdn.jsdelivr.net/npm/brython@3.13.2/brython.min.js"></script>
37
<script src="https://cdn.jsdelivr.net/npm/brython@3.13.2/brython_stdlib.js"></script>
38
</head>
39
<body onload="brython({debug: 1})">
40
<div id="output"></div>
41
<button id="click-me">Click Me</button>
42
43
<script type="text/python">
44
from browser import document, bind
45
from browser.html import P
46
47
# DOM manipulation
48
document["output"] <= P("Hello from Python!")
49
50
# Event handling
51
@bind(document["click-me"], 'click')
52
def handle_click(event):
53
document["output"] <= P("Button clicked!")
54
</script>
55
</body>
56
</html>
57
```
58
59
**Local Development Setup:**
60
61
```bash
62
# Install Brython CLI
63
pip install brython
64
65
# Initialize new project
66
mkdir my-brython-app
67
cd my-brython-app
68
brython-cli install
69
70
# Start development server
71
brython-cli start_server 8000
72
```
73
74
## Architecture
75
76
Brython consists of several key components:
77
78
- **CLI Tools**: Project initialization, package management, and development server
79
- **Runtime Engine**: JavaScript-based Python 3 interpreter running in browsers
80
- **Browser Module**: Python interface to DOM, events, and browser APIs
81
- **Standard Library**: Browser-compatible versions of Python standard modules
82
- **UI Framework**: Widget-based GUI toolkit for web applications
83
84
This architecture enables full-stack Python development where client-side logic runs as Python in the browser while maintaining compatibility with existing JavaScript libraries and browser APIs.
85
86
## Capabilities
87
88
### CLI Development Tools
89
90
Command-line interface for managing Brython projects, installing packages, creating distributions, and running development servers.
91
92
```python { .api }
93
# Main CLI commands accessed via brython-cli
94
def install(install_dir=".", no_demo=False): ...
95
def update(update_dir="."): ...
96
def add_package(package, dest_dir=None): ...
97
def make_package(package_name, src_dir=".", exclude_dirs=None, output_path=None): ...
98
def make_modules(output_path=None, reset=False, modules_paths=None): ...
99
def start_server(port=8000, bind="localhost"): ...
100
```
101
102
[CLI Tools](./cli-tools.md)
103
104
### Browser Runtime Engine
105
106
JavaScript-based Python interpreter that executes Python 3 code in web browsers with full language support.
107
108
```javascript { .api }
109
function brython(options?: BrythonOptions): void;
110
function $B.runPythonSource(src: string, options?: RunOptions): any;
111
function $B.py2js(src: string, module: string, locals_id?: string, parent_scope?: any): string;
112
```
113
114
[Runtime Engine](./runtime-engine.md)
115
116
### DOM and Browser Integration
117
118
Python interface to HTML DOM elements, events, and browser APIs with Pythonic syntax and full browser functionality access.
119
120
```python { .api }
121
# Core browser objects
122
browser.document: DOMDocument
123
browser.window: BrowserWindow
124
browser.console: Console
125
126
# Event binding decorator
127
def bind(element: Element, event: str, options: dict = None) -> Callable: ...
128
129
# Template engine for dynamic HTML
130
class Template:
131
def __init__(self, element: Element | str, callbacks: list = None): ...
132
def render(self, **kwargs) -> None: ...
133
```
134
135
[Browser Integration](./browser-integration.md)
136
137
### HTML Element Creation
138
139
Python classes for all HTML5 elements with attribute management, styling, and event handling capabilities.
140
141
```python { .api }
142
class DIV(Element): ...
143
class P(Element): ...
144
class A(Element): ...
145
class BUTTON(Element): ...
146
class INPUT(Element): ...
147
class FORM(Element): ...
148
class TABLE(Element): ...
149
# ... all HTML5 elements available
150
```
151
152
[HTML Elements](./html-elements.md)
153
154
### AJAX and Networking
155
156
HTTP request handling with Python-friendly interfaces for web service communication and data exchange.
157
158
```python { .api }
159
class Ajax:
160
def __init__(self): ...
161
def bind(self, event: str, callback: Callable) -> Ajax: ...
162
def open(self, method: str, url: str, async_: bool = True) -> None: ...
163
def send(self, data: Any = None) -> None: ...
164
```
165
166
[AJAX and Networking](./ajax-networking.md)
167
168
### Storage and Data Persistence
169
170
Browser storage APIs including localStorage, sessionStorage, and IndexedDB with Python interfaces.
171
172
```python { .api }
173
class LocalStorage:
174
def __getitem__(self, key: str) -> str: ...
175
def __setitem__(self, key: str, value: str) -> None: ...
176
def __delitem__(self, key: str) -> None: ...
177
178
class IndexedDB:
179
def __init__(self, name: str, version: int = 1): ...
180
def open(self) -> None: ...
181
def transaction(self, stores: list, mode: str = 'readonly') -> Transaction: ...
182
```
183
184
[Storage](./storage.md)
185
186
### Timers and Animation
187
188
Timer functions and animation frame requests for time-based functionality and smooth animations.
189
190
```python { .api }
191
def set_timeout(func: Callable, interval: int, *args) -> int: ...
192
def set_interval(func: Callable, interval: int, *args) -> int: ...
193
def clear_timeout(timer_id: int) -> None: ...
194
def clear_interval(timer_id: int) -> None: ...
195
def request_animation_frame(func: Callable) -> int: ...
196
```
197
198
[Timers and Animation](./timers-animation.md)
199
200
### UI Framework
201
202
Widget-based GUI toolkit with layout management, styling, and event handling for creating desktop-like web applications.
203
204
```python { .api }
205
class Widget:
206
def __init__(self, parent: Widget = None): ...
207
208
class Button(Widget):
209
def __init__(self, text: str = "", parent: Widget = None): ...
210
211
class Entry(Widget):
212
def __init__(self, value: str = "", parent: Widget = None): ...
213
214
class Dialog(Widget):
215
def __init__(self, title: str = "", parent: Widget = None): ...
216
```
217
218
[UI Framework](./ui-framework.md)
219
220
### WebSocket Communication
221
222
Real-time bidirectional communication with WebSocket support for live data and interactive applications.
223
224
```python { .api }
225
class WebSocket:
226
def __init__(self, url: str, protocols: list = None): ...
227
def send(self, data: str | bytes) -> None: ...
228
def close(self, code: int = 1000, reason: str = "") -> None: ...
229
```
230
231
[WebSocket](./websocket.md)
232
233
## Types
234
235
```python { .api }
236
# Configuration types
237
class BrythonOptions:
238
debug: int # Debug level 0-3
239
cache: bool # Enable module caching
240
indexeddb: bool # Use IndexedDB for caching
241
pythonpath: list[str] # Additional module paths
242
ids: list[str] # Specific script IDs to run
243
args: list[str] # Command line arguments
244
245
# DOM element base
246
class Element:
247
def __init__(self, content: str = "", **attrs): ...
248
def bind(self, event: str, callback: Callable) -> Element: ...
249
def unbind(self, event: str, callback: Callable = None) -> Element: ...
250
251
# Event handling
252
class Event:
253
target: Element
254
type: str
255
preventDefault: Callable
256
stopPropagation: Callable
257
258
# Browser objects
259
class DOMDocument:
260
def __getitem__(self, id: str) -> Element: ...
261
def createElement(self, tag: str) -> Element: ...
262
def createTextNode(self, text: str) -> TextNode: ...
263
264
class BrowserWindow:
265
location: Location
266
history: History
267
localStorage: Storage
268
sessionStorage: Storage
269
```