Published
Edited
May 14, 2019
Insert cell
Insert cell
brython = require('brython').catch(() => window.brython)
//or brython = require('brython@3.7.1/brython.js').catch(() => window.brython)
Insert cell
__BRYTHON__ = {
brython;
return window.__BRYTHON__;
}
Insert cell
// Tagged template literals - DO NOT USE ${ INSIDE brythonSrc
// https://github.com/brython-dev/brython/issues/1055#issuecomment-472862271
// runBrython(code) from Bryan Gin-ge Chen https://observablehq.com/d/9264b6145e1b1e1c
//Optional python source (libPyStr) can be added at the beginning in another tagged template literals (see pyLi)
function py(brythonSrc, libPyStr){ //ex. brythonSrc = Array [ "x=5\nprint(f'x=\n{x}')\n" ]
var raw = (libPyStr ? libPyStr+'\n' : '')
+ brythonSrc.raw.join('') //x=5
//print(f'x=\n{x}')
//
// https://talk.observablehq.com/t/execute-code-in-non-strict-mode/1728
// https://observablehq.com/@mootari/tracking-and-displaying-errors
try {
var br_js = (1,eval)(__BRYTHON__.python_to_js(raw))
} catch(err) {
err.message = err.args //err.message is used to show err. inf. in observable
console.error(err.message)
throw err
}
return br_js
}
Insert cell
{py`
x=5
print(f'x=\n{x}')
`; return 'py\`...\` test - check your console!'/*<- comment*/}
Insert cell
div0 = {
return html`<p>Your name is : <input id="zone" autocomplete="off" value="Test 0">
<button id="test">click !</button> <span id="echo2"><span>
`;
}
Insert cell
{
// wait for div0 cell to be evaluated
div0;
// python code won't work until the referenced elements are appended to the DOM
py`
print('\n Brython: (re)evaluating cell')
from browser import document
print('\n __BRYTHON__',__BRYTHON__.__MAGIC__,'\n','-'*17,'\n')

def echo(ev):
s = document["zone"].value
document["echo2"].text = f'Hello {s} !'
print(f'~ {s} ~')

btn = document["test"]; btn.unbind("click") # unbind, so re-evaluating this cell will be OK
btn.bind("click", echo)
`
return 'python: btn.bind("click", echo) - this line is just a comment in observablehq'
}
Insert cell
libPySrc = md`\`\`\`python
"""\
Additional source inserted in pyLi tagged template literals
"""
y=3+3
\`\`\``
Insert cell
// tagged template literals with python source (libPySrc) added at the beginning
function pyLi(brythonSrc){//brythonSrc = Array [ "x=5\nprint(f'x=\n{x}')\n" ]
return py (brythonSrc, libPySrc.innerText)
} //DO NOT USE ${ INSIDE brythonSrc !
Insert cell
{pyLi`
print(f'y=\n{y}')
`; return 'pyLi\`...\` test - check your console!'/*<- comment*/}
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more