Python-to-JavaScript transpiler that enables Python 3 development in web browsers with full DOM integration and standard library support
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
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.
Initialize and configure the Brython runtime environment in web browsers.
function brython(options?: BrythonOptions): void
/**
* Initialize Brython runtime and execute Python scripts.
*
* @param options - Configuration options for runtime
* @param options.debug - Debug level (0-3): 0=none, 1=python exceptions, 2+compile info, 3=all
* @param options.cache - Enable module caching for faster loading
* @param options.indexeddb - Use IndexedDB for persistent caching
* @param options.pythonpath - Additional paths for module resolution
* @param options.ids - Specific script element IDs to execute
* @param options.args - Command line arguments passed to sys.argv
* @param options.static_stdlib_import - Import standard library statically
* @param options.js_tab - Execute in web worker context
*/Usage:
<script>
// Basic initialization
brython();
// With debug enabled
brython({debug: 1});
// Advanced configuration
brython({
debug: 2,
cache: true,
indexeddb: true,
pythonpath: ['/custom/modules'],
ids: ['main-script', 'utils-script']
});
</script>Execute Python source code dynamically within the browser runtime.
function $B.runPythonSource(src: string, options?: RunOptions): any
/**
* Execute Python source code in browser context.
*
* @param src - Python source code as string
* @param options - Execution options
* @param options.locals_id - Local scope identifier
* @param options.module - Module name for execution context
* @returns Result of script execution
*/Usage:
// Execute Python code
const result = $B.runPythonSource(`
x = 10
y = 20
print(f"Sum: {x + y}")
x + y
`);
console.log(result); // 30
// With module context
$B.runPythonSource(`
import math
result = math.sqrt(16)
print(f"Square root: {result}")
`, {module: 'calculations'});Convert Python source code to executable JavaScript for optimization or analysis.
function $B.py2js(src: string, module: string, locals_id?: string, parent_scope?: any): string
/**
* Transpile Python source code to JavaScript.
*
* @param src - Python source code
* @param module - Module name for transpilation context
* @param locals_id - Local variables scope identifier
* @param parent_scope - Parent scope context
* @returns Transpiled JavaScript code
*/Usage:
// Transpile Python to JavaScript
const pythonCode = `
def greet(name):
return f"Hello, {name}!"
message = greet("World")
print(message)
`;
const jsCode = $B.py2js(pythonCode, '__main__');
console.log(jsCode); // Generated JavaScriptDynamic module loading and import resolution for Python modules.
function $B.import_module(name: string): any
/**
* Import Python module dynamically.
*
* @param name - Module name to import
* @returns Imported module object
*/
function $B.has_file(filename: string): boolean
/**
* Check if file exists in virtual file system.
*
* @param filename - File path to check
* @returns True if file exists
*/
function $B.add_files(files: {[path: string]: string}): void
/**
* Add files to virtual file system.
*
* @param files - Object mapping file paths to content
*/Usage:
// Dynamic module import
const mathModule = $B.import_module('math');
const result = mathModule.sqrt(25);
// File system operations
if ($B.has_file('config.py')) {
const config = $B.import_module('config');
}
// Add files to VFS
$B.add_files({
'utils.py': 'def helper(): return "Helper function"',
'data.json': '{"key": "value"}'
});Seamless conversion between Python and JavaScript objects and data types.
function $B.jsobj2pyobj(obj: any): any
/**
* Convert JavaScript object to Python object.
*
* @param obj - JavaScript object to convert
* @returns Python representation of the object
*/
function $B.pyobj2jsobj(obj: any): any
/**
* Convert Python object to JavaScript object.
*
* @param obj - Python object to convert
* @returns JavaScript representation of the object
*/Usage:
// JavaScript to Python conversion
const jsArray = [1, 2, 3, 4, 5];
const pyList = $B.jsobj2pyobj(jsArray);
// Python to JavaScript conversion
const pyDict = $B.runPythonSource("{'name': 'John', 'age': 30}");
const jsObject = $B.pyobj2jsobj(pyDict);
console.log(jsObject); // {name: 'John', age: 30}Configure and query runtime settings and environment.
function $B.get_page_option(option: string): any
/**
* Get runtime configuration option.
*
* @param option - Option name to retrieve
* @returns Option value
*/
function $B.set_debug(level: number): void
/**
* Set debug level for runtime.
*
* @param level - Debug level (0-3)
*/
// Runtime constants
const $B.brython_path: string // Path to Brython files
const $B.version_info: [number, number, number] // Version tupleUsage:
// Get configuration
const debugLevel = $B.get_page_option('debug');
const cachingEnabled = $B.get_page_option('cache');
// Set debug level
$B.set_debug(2);
// Access runtime info
console.log('Brython path:', $B.brython_path);
console.log('Version:', $B.version_info);Tools for debugging, error handling, and code analysis.
function $B.show_tokens(src: string): Array<Token>
/**
* Tokenize Python source code.
*
* @param src - Python source code
* @returns Array of tokens
*/
function $B.pythonToAST(code: string, filename: string, mode: string): AST
/**
* Parse Python code to Abstract Syntax Tree.
*
* @param code - Python source code
* @param filename - Source filename for error reporting
* @param mode - Parse mode ('exec', 'eval', 'single')
* @returns AST representation
*/
function $B.handle_error(error: Error): void
/**
* Handle runtime errors with proper Python error formatting.
*
* @param error - JavaScript/Python error object
*/Usage:
// Tokenize code
const tokens = $B.show_tokens('def hello(): print("Hello")');
console.log(tokens);
// Parse to AST
const ast = $B.pythonToAST('x = 1 + 2', '<string>', 'exec');
console.log(ast);
// Error handling
try {
$B.runPythonSource('invalid python code');
} catch (error) {
$B.handle_error(error);
}Manage files and modules in the browser's virtual file system.
function $B.update_VFS(scripts: {[name: string]: string}): void
/**
* Update Virtual File System with new scripts.
*
* @param scripts - Object mapping script names to content
*/
function $B.VFS_PREFIX: string
// Base path for virtual file system
interface VFSEntry {
content: string;
timestamp: number;
encoding?: string;
}Usage:
// Update VFS with new modules
$B.update_VFS({
'mymodule': 'def func(): return "Hello from module"',
'package/__init__': '# Package initialization',
'package/submodule': 'VALUE = 42'
});
// Access VFS information
console.log('VFS prefix:', $B.VFS_PREFIX);interface BrythonOptions {
debug?: number; // Debug level (0-3)
cache?: boolean; // Enable module caching
indexeddb?: boolean; // Use IndexedDB for caching
pythonpath?: string[]; // Additional module paths
ids?: string[]; // Specific script IDs to run
args?: string[]; // Command line arguments
static_stdlib_import?: boolean; // Static standard library import
js_tab?: boolean; // Web worker execution
}
interface RunOptions {
locals_id?: string; // Local scope identifier
module?: string; // Module name for context
}
interface Token {
type: string; // Token type
value: string; // Token value
start: [number, number]; // Start position [line, column]
end: [number, number]; // End position [line, column]
}
interface AST {
type: string; // AST node type
lineno?: number; // Line number
col_offset?: number; // Column offset
[key: string]: any; // Additional node properties
}// 1. Load Brython core files
<script src="brython.js"></script>
<script src="brython_stdlib.js"></script>
// 2. Initialize runtime
<script>brython({debug: 1});</script>
// 3. Python scripts execute automatically
<script type="text/python">
from browser import document
print("Brython is ready!")
</script>The runtime provides comprehensive error handling that maps JavaScript errors to Python exceptions:
// Python exceptions are properly formatted
try {
$B.runPythonSource('1 / 0');
} catch (error) {
// Error includes Python traceback information
console.error(error.python_traceback);
}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.
Install with Tessl CLI
npx tessl i tessl/pypi-brython