"use strict";(self.webpackChunkdocs=self.webpackChunkdocs||[]).push([["3119"],{1733:function(e,t,n){n.r(t),n.d(t,{default:()=>u,frontMatter:()=>a,metadata:()=>s,assets:()=>d,toc:()=>c,contentTitle:()=>l});var s=JSON.parse('{"id":"languages/python","title":"Python","description":"LiveCodes can run Python in the browser using Brython, a Python 3 implementation for client-side web programming.","source":"@site/docs/languages/python.mdx","sourceDirName":"languages","slug":"/languages/python","permalink":"/docs/languages/python","draft":false,"unlisted":false,"editUrl":"https://github.com/live-codes/livecodes/tree/develop/docs/docs/languages/python.mdx","tags":[],"version":"current","frontMatter":{},"sidebar":"docsSidebar","previous":{"title":"Python (Wasm)","permalink":"/docs/languages/python-wasm"},"next":{"title":"R","permalink":"/docs/languages/r"}}'),r=n("5893"),i=n("65");n("8500");var o=n("3365");let a={},l="Python",d={},c=[{value:"Usage",id:"usage",level:2},{value:"Standard Library",id:"standard-library",level:3},{value:"JavaScript Interoperability",id:"javascript-interoperability",level:3},{value:"Language Info",id:"language-info",level:2},{value:"Name",id:"name",level:3},{value:"Extensions",id:"extensions",level:3},{value:"Editor",id:"editor",level:3},{value:"Compiler",id:"compiler",level:2},{value:"Version",id:"version",level:3},{value:"Code Formatting",id:"code-formatting",level:2},{value:"Example Usage",id:"example-usage",level:2},{value:"Starter Template",id:"starter-template",level:2},{value:"Links",id:"links",level:2}];function h(e){let t={a:"a",admonition:"admonition",code:"code",h1:"h1",h2:"h2",h3:"h3",header:"header",li:"li",p:"p",ul:"ul",...(0,i.a)(),...e.components};return(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(t.header,{children:(0,r.jsx)(t.h1,{id:"python",children:"Python"})}),"\n","\n",(0,r.jsxs)(t.p,{children:["LiveCodes can run Python in the browser using ",(0,r.jsx)(t.a,{href:"https://brython.info/",children:"Brython"}),", a Python 3 implementation for client-side web programming."]}),"\n",(0,r.jsxs)(t.admonition,{title:"Note",type:"info",children:[(0,r.jsx)(t.p,{children:"Brython is a light-weight Python interpreter written in JavaScript. However, It does not allow loading external packages from PyPI."}),(0,r.jsxs)(t.p,{children:["If you need to import external packages including scientific Python packages like numpy, pandas, scipy, matplotlib, and scikit-learn, you may want to use ",(0,r.jsx)(t.a,{href:"/docs/languages/python-wasm",children:"Python (Wasm)"}),", which uses Pyodide the ",(0,r.jsx)(t.a,{href:"https://github.com/python/cpython",children:"CPython"})," port to WebAssembly."]})]}),"\n",(0,r.jsx)(t.h2,{id:"usage",children:"Usage"}),"\n",(0,r.jsx)(t.p,{children:"LiveCodes runs Python code in the browser. There is no server required to run the code and no need to install Python."}),"\n",(0,r.jsxs)(t.p,{children:["In addition, since the Python code is running on the client-side, it has access to the ",(0,r.jsx)(t.a,{href:"#javascript-interoperability",children:"JavaScript scope"}),", including the page DOM and browser APIs. See the ",(0,r.jsx)(t.a,{href:"#starter-template",children:"starter template"})," for an example."]}),"\n",(0,r.jsx)(t.h3,{id:"standard-library",children:"Standard Library"}),"\n",(0,r.jsxs)(t.p,{children:["Many modules of the Python standard library are functional. See ",(0,r.jsx)(t.a,{href:"https://brython.info/static_doc/en/stdlib.html",children:"Brython distribution"})," for details."]}),"\n",(0,r.jsx)(t.h3,{id:"javascript-interoperability",children:"JavaScript Interoperability"}),"\n",(0,r.jsxs)(t.p,{children:["Interaction with the page DOM and JavaScript can be achieved using ",(0,r.jsx)(t.a,{href:"https://brython.info/static_doc/en/browser.html",children:(0,r.jsx)(t.code,{children:"browser"})})," and ",(0,r.jsx)(t.a,{href:"https://brython.info/static_doc/en/javascript.html",children:(0,r.jsx)(t.code,{children:"javascript"})})," modules. See ",(0,r.jsx)(t.a,{href:"https://brython.info/static_doc/en/dom_api.html",children:"this guide"})," for using the DOM API."]}),"\n",(0,r.jsxs)(t.p,{children:["Check the ",(0,r.jsx)(t.a,{href:"#starter-template",children:"starter template"})," for an example."]}),"\n",(0,r.jsx)(t.h2,{id:"language-info",children:"Language Info"}),"\n",(0,r.jsx)(t.h3,{id:"name",children:"Name"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:"python"})}),"\n",(0,r.jsx)(t.h3,{id:"extensions",children:"Extensions"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:".py"})}),"\n",(0,r.jsx)(t.h3,{id:"editor",children:"Editor"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.code,{children:"script"})}),"\n",(0,r.jsx)(t.h2,{id:"compiler",children:"Compiler"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"https://brython.info/",children:"Brython"})}),"\n",(0,r.jsx)(t.h3,{id:"version",children:"Version"}),"\n",(0,r.jsx)(t.p,{children:"Brython v3.12.3, running Python v3.12"}),"\n",(0,r.jsx)(t.h2,{id:"code-formatting",children:"Code Formatting"}),"\n",(0,r.jsx)(t.p,{children:"Not supported."}),"\n",(0,r.jsx)(t.h2,{id:"example-usage",children:"Example Usage"}),"\n",(0,r.jsx)(o.Z,{template:"python",height:"80vh"}),"\n",(0,r.jsx)(t.h2,{id:"starter-template",children:"Starter Template"}),"\n",(0,r.jsx)(t.p,{children:(0,r.jsx)(t.a,{href:"https://livecodes.io/?template=python",children:"https://livecodes.io/?template=python"})}),"\n",(0,r.jsx)(t.h2,{id:"links",children:"Links"}),"\n",(0,r.jsxs)(t.ul,{children:["\n",(0,r.jsx)(t.li,{children:(0,r.jsx)(t.a,{href:"https://www.python.org/",children:"Python"})}),"\n",(0,r.jsx)(t.li,{children:(0,r.jsx)(t.a,{href:"https://brython.info/",children:"Brython"})}),"\n",(0,r.jsxs)(t.li,{children:[(0,r.jsx)(t.a,{href:"/docs/languages/python-wasm",children:"Python (Wasm)"})," in LiveCodes"]}),"\n"]})]})}function u(e={}){let{wrapper:t}={...(0,i.a)(),...e.components};return t?(0,r.jsx)(t,{...e,children:(0,r.jsx)(h,{...e})}):h(e)}},3365:function(e,t,n){n.d(t,{Z:()=>f});var s=n("5893"),r=n("4200"),i=n("7294"),o=n("8294");function a(e){let t=(0,i.useRef)(null),[n,r]=(0,i.useState)(e.className||""),[a,l]=(0,i.useState)(e.style||{}),[d,c]=(0,i.useState)(e.height),[h,u]=(0,i.useState)(),[p,m]=(0,i.useState)(JSON.stringify(e.config||"")),[g,f]=(0,i.useState)("");return(0,i.useEffect)(()=>{if(!t.current)return;let{className:n,style:s,height:i,sdkReady:a,config:d,...y}=e;if(r(n||""),l(s||{}),c(i),h&&g===JSON.stringify(y)){if(p===JSON.stringify(d))return;m(JSON.stringify(d)),"string"==typeof d?fetch(d).then(e=>e.json()).then(e=>{h?.setConfig(e)}):d&&h.setConfig(d)}else f(JSON.stringify(y)),h?.destroy(),(0,o.T)(t.current,{config:d,...y}).then(e=>{u(e),"function"==typeof a&&a(e)})},[e]),(0,i.useEffect)(()=>()=>{h?.destroy()},[]),(0,s.jsx)("div",{ref:t,className:n,style:a,"data-height":d})}var l=n("1858"),d=n("3262"),c=n("1705"),h=n("7645"),u=n("8168"),p=n("8228"),m=n("5050");function g(e){let[t,n]=(0,i.useState)(e.js),[r,o]=(0,i.useState)(e.ts),[a,l]=(0,i.useState)(e.react),[g,f]=(0,i.useState)(e.vue),[y,v]=(0,i.useState)(e.svelte),x="3.7rem",[j,b]=(0,i.useState)(!0),[w,P]=(0,i.useState)(x),S=(0,i.useRef)(null),C=()=>{setTimeout(()=>{P(`calc(${S.current.offsetHeight}px + ${x})`)},5),setTimeout(()=>{P(`calc(${S.current.offsetHeight}px + ${x})`)},255)};return(0,i.useEffect)(()=>{if(d.Z.canUseDOM){let e=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"js";try{return window.prettier?.format(e,{parser:"html"===t?"html":"babel",plugins:window.prettierPlugins})}catch{return e}};n(e(t,"js")),o(e(r,"ts")),l(e(a,"jsx")),f(e(g,"html")),v(e(y,"html"))}},[]),(0,s.jsxs)("details",{className:`alert alert--info ${m.Z.details} ${p.Z.details}`,"data-collapsed":j,style:{height:j?x:w,overflow:"hidden",willChange:"height",transition:`height ${j?"250ms":"265ms"} ease-in-out 0s`,margin:"1em 0"},children:[(0,s.jsx)("summary",{onClick:()=>{b(!j),C()},children:"show code"}),(0,s.jsx)("div",{ref:S,style:{display:"block",overflow:"hidden"},children:(0,s.jsx)("div",{className:m.Z.collapsibleContent,children:(0,s.jsxs)(u.Z,{groupId:"sdk-code",children:[(0,s.jsx)(h.Z,{value:"js",label:"JS",attributes:{onMouseDown:C},children:(0,s.jsx)(c.Z,{language:"js",children:t})}),(0,s.jsx)(h.Z,{value:"ts",label:"TS",attributes:{onMouseDown:C},children:(0,s.jsx)(c.Z,{language:"ts",children:r})}),(0,s.jsx)(h.Z,{value:"react",label:"React",attributes:{onMouseDown:C},children:(0,s.jsx)(c.Z,{language:"jsx",children:a})}),(0,s.jsx)(h.Z,{value:"vue",label:"Vue",attributes:{onMouseDown:C},children:(0,s.jsx)(c.Z,{language:"html",children:g})}),(0,s.jsx)(h.Z,{value:"svelte",label:"Svelte",attributes:{onMouseDown:C},children:(0,s.jsx)(c.Z,{language:"html",children:y})})]})})})]})}function f(e){let{className:t,style:n,showCode:i,height:o,...d}=e,{colorMode:c}=(0,r.I)(),h=e=>JSON.stringify(e,null,2),u=` import { createPlayground } from 'livecodes'; const options = ${h(d)}; createPlayground('#container', options); `.trimStart(),p=` import { createPlayground, type EmbedOptions } from 'livecodes'; const options: EmbedOptions = ${h(d)}; createPlayground('#container', options); `.trimStart(),m=` import LiveCodes from 'livecodes/react'; export default function App() { const options = ${h(d)}; return (); } `.trimStart(),f=` `,y=`
`.trimStart();return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(a,{className:`container_Egsj ${e.className}`,style:{height:o||"50vh",...e.style},appUrl:l.G,...e,config:{theme:c,themeColor:"hsl(215, 8%, 60%)",..."object"==typeof e.config?e.config:{}}}),!1!==e.showCode&&(0,s.jsx)(g,{js:u,ts:p,react:m,vue:f,svelte:y})]})}},8500:function(e,t,n){n.d(t,{Z:()=>d});var s=n("5893");n("7294");var r=n("6735");function i(e){let{children:t,fallback:n}=e;return(0,r.Z)()?(0,s.jsx)(s.Fragment,{children:t?.()}):n??null}var o=n("1705"),a=n("8294"),l=n("1858");function d(e){let{params:t,config:n,code:r,language:d="js",codeTitle:c="",showLineNumbers:h=!1,formatCode:u=!0,linkText:p="Run in LiveCodes",style:m={},className:g=""}=e,f=(0,a.r)({appUrl:l.G,params:t,config:n});return(0,s.jsxs)("div",{style:{marginBottom:"30px",...m},className:g,children:[r&&(0,s.jsx)(i,{children:()=>(0,s.jsx)(o.Z,{language:d,title:c,showLineNumbers:h,children:u?function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"js";return window.prettier?.format(e,{parser:"html"===t?"html":"babel",plugins:window.prettierPlugins})}(r,d):r})}),(0,s.jsxs)("a",{href:f,target:"_blank",rel:"noreferrer",children:[p,(0,s.jsx)("svg",{width:"12",height:"12","aria-hidden":"true",viewBox:"0 0 24 24",className:"iconExternalLink_node_modules-@docusaurus-theme-classic-lib-theme-Icon-ExternalLink-styles-module",style:{marginLeft:"4px"},children:(0,s.jsx)("path",{fill:"currentColor",d:"M21 13v10h-21v-19h12v2h-10v15h17v-8h2zm3-12h-10.988l4.035 4-6.977 7.07 2.828 2.828 6.977-7.07 4.125 4.172v-11z"})})]})]})}},8294:function(e,t,n){n.d(t,{T:function(){return r},r:function(){return i}});var s=n(7728);async function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};"object"!=typeof e||e instanceof HTMLElement||!e.headless&&"headless"!==e.view||(t=e,e=null);let{config:n={},headless:s,loading:r="lazy",view:o}=t,a=s||"headless"===o,l=null,d=null;if("string"==typeof e)l=document.querySelector(e);else if(e instanceof HTMLElement)l=e;else if(!(a&&"object"==typeof e))throw Error("A valid container element is required.");if(!l){if(a)S(l=document.createElement("div")),document.body.appendChild(l);else throw Error(`Cannot find element: "${e}"`)}let c=new URL(i(t)),h=c.origin;c.searchParams.set("embed","true"),c.searchParams.set("loading",a?"eager":r),c.searchParams.set("sdkVersion",process.env.SDK_VERSION||"latest"),"object"==typeof n&&Object.keys(n).length>0&&c.searchParams.set("config","sdk");let u=t.params;"object"==typeof u&&Object.keys(u).length>0&&JSON.stringify(u).length<1800&&Object.keys(u).forEach(e=>{c.searchParams.set(e,encodeURIComponent(String(u[e])))});let p=!1,m="Cannot call API methods after calling `destroy()`.",g=await new Promise(e=>{if(!l)return;let t=l.dataset.height||l.style.height;if(t&&!a){let e=isNaN(Number(t))?t:t+"px";l.style.height=e}"false"===l.dataset.defaultStyles||a||(l.style.backgroundColor||="#fff",l.style.border||="1px solid black",l.style.borderRadius||="8px",l.style.boxSizing||="border-box",l.style.padding||="0",l.style.width||="100%",l.style.height||=l.style.height||"300px",l.style.minHeight="200px",l.style.flexGrow="1",l.style.overflow||="hidden",l.style.resize||="vertical");let s="livecodes",i=l.querySelector(`iframe.${s}`),o=i||document.createElement("iframe");o.classList.add(s),o.setAttribute("allow","accelerometer; camera; encrypted-media; display-capture; geolocation; gyroscope; microphone; midi; clipboard-read; clipboard-write; web-share"),o.setAttribute("allowtransparency","true"),o.setAttribute("allowpaymentrequest","true"),o.setAttribute("allowfullscreen","true"),o.setAttribute("sandbox","allow-same-origin allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts"),o.setAttribute("loading","eager"===r?"eager":"lazy"),a?S(o):(o.style.height="100%",o.style.minHeight="200px",o.style.width="100%",o.style.margin="0",o.style.border="0",o.style.borderRadius=l.style.borderRadius),addEventListener("message",function e(t){t.source===o.contentWindow&&t.origin===h&&t.data?.type==="livecodes-init"&&(removeEventListener("message",e),d=Number(t.data.payload.appVersion.replace(/^v/,"")))}),(!d||d<46)&&addEventListener("message",function e(t){t.source===o.contentWindow&&t.origin===h&&t.data?.type==="livecodes-get-config"&&(removeEventListener("message",e),o.contentWindow?.postMessage({type:"livecodes-config",payload:n},h))}),o.onload=()=>{e(o)},o.src=c.href,i||l.appendChild(o)}),f=new Promise(e=>{addEventListener("message",function t(n){n.source===g.contentWindow&&n.origin===h&&n.data?.type==="livecodes-ready"&&(removeEventListener("message",t),e(),f.settled=!0)})}),y=()=>p?Promise.reject(m):new Promise(async e=>{f.settled&&e(),g.contentWindow?.postMessage({type:"livecodes-load"},h),await f,e()}),v=(e,t)=>new Promise(async(n,s)=>{if(p)return s(m);await y();let r=C();addEventListener("message",function t(i){if(i.source===g.contentWindow&&i.origin===h&&i.data?.type==="livecodes-api-response"&&i.data?.id===r&&i.data.method===e){removeEventListener("message",t);let e=i.data.payload;e?.error?s(e.error):n(e)}}),g.contentWindow?.postMessage({method:e,id:r,args:t},h)}),x={},j=["load","ready","code","console","tests","destroy"],b=(e,t)=>{if(p)throw Error(m);return j.includes(e)?(v("watch",[e]),x[e]||(x[e]=[]),x[e]?.push(t),{remove:()=>{x[e]=x[e]?.filter(e=>e!==t),x[e]?.length===0&&v("watch",[e,"unsubscribe"])}}):{remove:()=>void 0}},w=e=>({"livecodes-app-loaded":"load","livecodes-ready":"ready","livecodes-change":"code","livecodes-console":"console","livecodes-test-results":"tests","livecodes-destroy":"destroy"})[e];addEventListener("message",async e=>{let t=w(e.data?.type??"");if(e.source!==g.contentWindow||e.origin!==h||!t||!x[t])return;let n=e.data?.payload;x[t]?.forEach(e=>{e(n)})});let P=()=>{Object.values(x).forEach(e=>{e.length=0}),g?.remove?.(),p=!0};function S(e){e.style.position="absolute",e.style.top="0",e.style.visibility="hidden",e.style.opacity="0"}"lazy"===r&&"IntersectionObserver"in window&&new IntersectionObserver((e,t)=>{e.forEach(async e=>{e.isIntersecting&&(await y(),t.unobserve(l))})},{rootMargin:"150px"}).observe(l);let C=()=>(String(Math.random())+Date.now().toFixed()).replace("0.","");return{load:()=>y(),run:()=>v("run"),format:e=>v("format",[e]),getShareUrl:e=>v("getShareUrl",[e]),getConfig:e=>v("getConfig",[e]),setConfig:e=>v("setConfig",[e]),getCode:()=>v("getCode"),show:(e,t)=>v("show",[e,t]),runTests:()=>v("runTests"),onChange:e=>b("code",e),watch:b,exec:function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),s=1;sf.settled?v("destroy").then(P):p?Promise.reject(m):(P(),Promise.resolve())}}function i(){let e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{appUrl:n="https://livecodes.io",params:r={},config:i={},headless:o,import:a,lite:l,view:d,...c}=t;try{e=new URL(n)}catch{throw Error(`${n} is not a valid URL.`)}let h=new URLSearchParams;Object.entries(c).forEach(t=>{let[n,s]=t;void 0!==s&&e.searchParams.set(n,String(s))});let u="headless"===t.view||o;if(l&&(console.warn('Deprecation notice: "lite" option is deprecated. Use "config: { mode: \'lite\' }" instead.'),"object"==typeof i&&null==i.mode?i.mode="lite":e.searchParams.set("lite","true")),d&&(console.warn('Deprecation notice: The "view" option has been moved to "config.view". For headless mode use "headless: true".'),"object"==typeof i&&null==i.view&&"headless"!==d?i.view=d:e.searchParams.set("view",d)),"string"==typeof i)try{new URL(i),e.searchParams.set("config",encodeURIComponent(i))}catch{throw Error('"config" is not a valid URL or configuration object.')}else i&&"object"==typeof i&&Object.keys(i).length>0&&(i.title&&"Untitled Project"!==i.title&&e.searchParams.set("title",i.title),i.description&&i.description.length>0&&e.searchParams.set("description",i.description),h.set("config","code/"+(0,s.compressToEncodedURIComponent)(JSON.stringify(i))));if(r&&"object"==typeof r&&Object.keys(r).length>0)try{h.set("params",(0,s.compressToEncodedURIComponent)(JSON.stringify(r)))}catch{Object.keys(r).forEach(t=>{e.searchParams.set(t,encodeURIComponent(String(r[t])))})}return a&&e.searchParams.set("x",encodeURIComponent(a)),u&&e.searchParams.set("headless","true"),e.hash=h.toString(),e.href}},65:function(e,t,n){n.d(t,{Z:function(){return a},a:function(){return o}});var s=n(7294);let r={},i=s.createContext(r);function o(e){let t=s.useContext(i);return s.useMemo(function(){return"function"==typeof e?e(t):{...t,...e}},[t,e])}function a(e){let t;return t=e.disableParentContext?"function"==typeof e.components?e.components(r):e.components||r:o(e.components),s.createElement(i.Provider,{value:t},e.children)}}}]);