or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

ajax-networking.mdbrowser-integration.mdcli-tools.mdhtml-elements.mdindex.mdruntime-engine.mdstorage.mdtimers-animation.mdui-framework.mdwebsocket.md

runtime-engine.mddocs/

0

# Runtime Engine

1

2

JavaScript-based Python interpreter that executes Python 3 code in web browsers with full language support. The runtime engine transpiles Python code to JavaScript and provides a complete Python execution environment.

3

4

## Capabilities

5

6

### Main Initialization

7

8

Initialize and configure the Brython runtime environment in web browsers.

9

10

```javascript { .api }

11

function brython(options?: BrythonOptions): void

12

/**

13

* Initialize Brython runtime and execute Python scripts.

14

*

15

* @param options - Configuration options for runtime

16

* @param options.debug - Debug level (0-3): 0=none, 1=python exceptions, 2+compile info, 3=all

17

* @param options.cache - Enable module caching for faster loading

18

* @param options.indexeddb - Use IndexedDB for persistent caching

19

* @param options.pythonpath - Additional paths for module resolution

20

* @param options.ids - Specific script element IDs to execute

21

* @param options.args - Command line arguments passed to sys.argv

22

* @param options.static_stdlib_import - Import standard library statically

23

* @param options.js_tab - Execute in web worker context

24

*/

25

```

26

27

**Usage:**

28

```html

29

<script>

30

// Basic initialization

31

brython();

32

33

// With debug enabled

34

brython({debug: 1});

35

36

// Advanced configuration

37

brython({

38

debug: 2,

39

cache: true,

40

indexeddb: true,

41

pythonpath: ['/custom/modules'],

42

ids: ['main-script', 'utils-script']

43

});

44

</script>

45

```

46

47

### Script Execution

48

49

Execute Python source code dynamically within the browser runtime.

50

51

```javascript { .api }

52

function $B.runPythonSource(src: string, options?: RunOptions): any

53

/**

54

* Execute Python source code in browser context.

55

*

56

* @param src - Python source code as string

57

* @param options - Execution options

58

* @param options.locals_id - Local scope identifier

59

* @param options.module - Module name for execution context

60

* @returns Result of script execution

61

*/

62

```

63

64

**Usage:**

65

```javascript

66

// Execute Python code

67

const result = $B.runPythonSource(`

68

x = 10

69

y = 20

70

print(f"Sum: {x + y}")

71

x + y

72

`);

73

console.log(result); // 30

74

75

// With module context

76

$B.runPythonSource(`

77

import math

78

result = math.sqrt(16)

79

print(f"Square root: {result}")

80

`, {module: 'calculations'});

81

```

82

83

### Code Transpilation

84

85

Convert Python source code to executable JavaScript for optimization or analysis.

86

87

```javascript { .api }

88

function $B.py2js(src: string, module: string, locals_id?: string, parent_scope?: any): string

89

/**

90

* Transpile Python source code to JavaScript.

91

*

92

* @param src - Python source code

93

* @param module - Module name for transpilation context

94

* @param locals_id - Local variables scope identifier

95

* @param parent_scope - Parent scope context

96

* @returns Transpiled JavaScript code

97

*/

98

```

99

100

**Usage:**

101

```javascript

102

// Transpile Python to JavaScript

103

const pythonCode = `

104

def greet(name):

105

return f"Hello, {name}!"

106

107

message = greet("World")

108

print(message)

109

`;

110

111

const jsCode = $B.py2js(pythonCode, '__main__');

112

console.log(jsCode); // Generated JavaScript

113

```

114

115

### Module System

116

117

Dynamic module loading and import resolution for Python modules.

118

119

```javascript { .api }

120

function $B.import_module(name: string): any

121

/**

122

* Import Python module dynamically.

123

*

124

* @param name - Module name to import

125

* @returns Imported module object

126

*/

127

128

function $B.has_file(filename: string): boolean

129

/**

130

* Check if file exists in virtual file system.

131

*

132

* @param filename - File path to check

133

* @returns True if file exists

134

*/

135

136

function $B.add_files(files: {[path: string]: string}): void

137

/**

138

* Add files to virtual file system.

139

*

140

* @param files - Object mapping file paths to content

141

*/

142

```

143

144

**Usage:**

145

```javascript

146

// Dynamic module import

147

const mathModule = $B.import_module('math');

148

const result = mathModule.sqrt(25);

149

150

// File system operations

151

if ($B.has_file('config.py')) {

152

const config = $B.import_module('config');

153

}

154

155

// Add files to VFS

156

$B.add_files({

157

'utils.py': 'def helper(): return "Helper function"',

158

'data.json': '{"key": "value"}'

159

});

160

```

161

162

### Object Conversion

163

164

Seamless conversion between Python and JavaScript objects and data types.

165

166

```javascript { .api }

167

function $B.jsobj2pyobj(obj: any): any

168

/**

169

* Convert JavaScript object to Python object.

170

*

171

* @param obj - JavaScript object to convert

172

* @returns Python representation of the object

173

*/

174

175

function $B.pyobj2jsobj(obj: any): any

176

/**

177

* Convert Python object to JavaScript object.

178

*

179

* @param obj - Python object to convert

180

* @returns JavaScript representation of the object

181

*/

182

```

183

184

**Usage:**

185

```javascript

186

// JavaScript to Python conversion

187

const jsArray = [1, 2, 3, 4, 5];

188

const pyList = $B.jsobj2pyobj(jsArray);

189

190

// Python to JavaScript conversion

191

const pyDict = $B.runPythonSource("{'name': 'John', 'age': 30}");

192

const jsObject = $B.pyobj2jsobj(pyDict);

193

console.log(jsObject); // {name: 'John', age: 30}

194

```

195

196

### Runtime Configuration

197

198

Configure and query runtime settings and environment.

199

200

```javascript { .api }

201

function $B.get_page_option(option: string): any

202

/**

203

* Get runtime configuration option.

204

*

205

* @param option - Option name to retrieve

206

* @returns Option value

207

*/

208

209

function $B.set_debug(level: number): void

210

/**

211

* Set debug level for runtime.

212

*

213

* @param level - Debug level (0-3)

214

*/

215

216

// Runtime constants

217

const $B.brython_path: string // Path to Brython files

218

const $B.version_info: [number, number, number] // Version tuple

219

```

220

221

**Usage:**

222

```javascript

223

// Get configuration

224

const debugLevel = $B.get_page_option('debug');

225

const cachingEnabled = $B.get_page_option('cache');

226

227

// Set debug level

228

$B.set_debug(2);

229

230

// Access runtime info

231

console.log('Brython path:', $B.brython_path);

232

console.log('Version:', $B.version_info);

233

```

234

235

### Debugging and Introspection

236

237

Tools for debugging, error handling, and code analysis.

238

239

```javascript { .api }

240

function $B.show_tokens(src: string): Array<Token>

241

/**

242

* Tokenize Python source code.

243

*

244

* @param src - Python source code

245

* @returns Array of tokens

246

*/

247

248

function $B.pythonToAST(code: string, filename: string, mode: string): AST

249

/**

250

* Parse Python code to Abstract Syntax Tree.

251

*

252

* @param code - Python source code

253

* @param filename - Source filename for error reporting

254

* @param mode - Parse mode ('exec', 'eval', 'single')

255

* @returns AST representation

256

*/

257

258

function $B.handle_error(error: Error): void

259

/**

260

* Handle runtime errors with proper Python error formatting.

261

*

262

* @param error - JavaScript/Python error object

263

*/

264

```

265

266

**Usage:**

267

```javascript

268

// Tokenize code

269

const tokens = $B.show_tokens('def hello(): print("Hello")');

270

console.log(tokens);

271

272

// Parse to AST

273

const ast = $B.pythonToAST('x = 1 + 2', '<string>', 'exec');

274

console.log(ast);

275

276

// Error handling

277

try {

278

$B.runPythonSource('invalid python code');

279

} catch (error) {

280

$B.handle_error(error);

281

}

282

```

283

284

### Virtual File System

285

286

Manage files and modules in the browser's virtual file system.

287

288

```javascript { .api }

289

function $B.update_VFS(scripts: {[name: string]: string}): void

290

/**

291

* Update Virtual File System with new scripts.

292

*

293

* @param scripts - Object mapping script names to content

294

*/

295

296

function $B.VFS_PREFIX: string

297

// Base path for virtual file system

298

299

interface VFSEntry {

300

content: string;

301

timestamp: number;

302

encoding?: string;

303

}

304

```

305

306

**Usage:**

307

```javascript

308

// Update VFS with new modules

309

$B.update_VFS({

310

'mymodule': 'def func(): return "Hello from module"',

311

'package/__init__': '# Package initialization',

312

'package/submodule': 'VALUE = 42'

313

});

314

315

// Access VFS information

316

console.log('VFS prefix:', $B.VFS_PREFIX);

317

```

318

319

## Configuration Types

320

321

```javascript { .api }

322

interface BrythonOptions {

323

debug?: number; // Debug level (0-3)

324

cache?: boolean; // Enable module caching

325

indexeddb?: boolean; // Use IndexedDB for caching

326

pythonpath?: string[]; // Additional module paths

327

ids?: string[]; // Specific script IDs to run

328

args?: string[]; // Command line arguments

329

static_stdlib_import?: boolean; // Static standard library import

330

js_tab?: boolean; // Web worker execution

331

}

332

333

interface RunOptions {

334

locals_id?: string; // Local scope identifier

335

module?: string; // Module name for context

336

}

337

338

interface Token {

339

type: string; // Token type

340

value: string; // Token value

341

start: [number, number]; // Start position [line, column]

342

end: [number, number]; // End position [line, column]

343

}

344

345

interface AST {

346

type: string; // AST node type

347

lineno?: number; // Line number

348

col_offset?: number; // Column offset

349

[key: string]: any; // Additional node properties

350

}

351

```

352

353

## Runtime Lifecycle

354

355

### Initialization Sequence

356

357

```javascript

358

// 1. Load Brython core files

359

<script src="brython.js"></script>

360

<script src="brython_stdlib.js"></script>

361

362

// 2. Initialize runtime

363

<script>brython({debug: 1});</script>

364

365

// 3. Python scripts execute automatically

366

<script type="text/python">

367

from browser import document

368

print("Brython is ready!")

369

</script>

370

```

371

372

### Module Loading Process

373

374

1. **Import statement processed** by Python code

375

2. **Module resolution** checks VFS and paths

376

3. **Source loading** from VFS or HTTP request

377

4. **Transpilation** to JavaScript if needed

378

5. **Execution** in isolated module scope

379

6. **Caching** for future imports

380

381

### Error Handling

382

383

The runtime provides comprehensive error handling that maps JavaScript errors to Python exceptions:

384

385

```javascript

386

// Python exceptions are properly formatted

387

try {

388

$B.runPythonSource('1 / 0');

389

} catch (error) {

390

// Error includes Python traceback information

391

console.error(error.python_traceback);

392

}

393

```

394

395

This runtime engine provides a complete Python 3 execution environment in browsers, enabling full-featured Python development for web applications while maintaining compatibility with browser APIs and JavaScript integration.