PyScript and the magic of Python in the browser
This is a modal window.
The media could not be loaded, either because the server or network failed or because the format is not supported.
Formal Metadata
Title |
| |
Title of Series | ||
Number of Parts | 141 | |
Author | ||
License | CC Attribution - NonCommercial - ShareAlike 4.0 International: You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this | |
Identifiers | 10.5446/68713 (DOI) | |
Publisher | ||
Release Date | ||
Language |
Content Metadata
Subject Area | ||
Genre | ||
Abstract |
|
EuroPython 202360 / 141
8
17
22
26
27
31
42
48
52
55
56
59
64
66
67
72
73
77
79
83
86
87
95
99
103
105
113
114
115
118
119
123
129
131
135
139
140
141
00:00
Web browserStatisticsChord (peer-to-peer)Coma BerenicesFood energySoftware frameworkView (database)Internet service providerPattern recognitionPerfect groupWeb browserOpen sourceInterpreter (computing)Computing platformCompilation albumQuicksortScripting languageBefehlsprozessorRevision controlVirtualizationCodeCuboidProjective planeCore dumpSpeech synthesisSource codeWordPerturbation theoryDisk read-and-write headLetterpress printingData miningFormal languageSoftware frameworkBoilerplate (text)Web 2.0Presentation of a groupDigital photographyComputer animationMeeting/Interview
04:54
Computer virusPrice indexView (database)Food energyTurbo-CodeWeb browserComputer fileRevision controlInterpreter (computing)Context awarenessMicrocontrollerIntegrated development environmentElement (mathematics)Content (media)Letterpress printingSocial classQuicksortCodeMedical imagingInheritance (object-oriented programming)Scripting languageFunctional (mathematics)View (database)ImplementationPointer (computer programming)Moment (mathematics)Computer animationXML
07:50
Presentation of a groupComa BerenicesSource codeSemiconductor memoryInterpreter (computing)Scripting languageLine (geometry)Web pageEvent horizonQuicksortWeb browserStructural loadFunctional (mathematics)Boilerplate (text)CodeMereologyString (computer science)Cycle (graph theory)Video gameMoment (mathematics)Element (mathematics)Letterpress printingVideoconferencingComputing platformMobile appSystem callRadical (chemistry)Computer fileNeuroinformatikContent (media)Free variables and bound variablesCartesian coordinate systemProcess (computing)Revision controlGodDisk read-and-write headPoint (geometry)Social classObject (grammar)Memory managementWeb 2.0Set (mathematics)Computer animationLecture/Conference
13:47
PasswordSign (mathematics)Food energyWebsiteComa BerenicesOpen setMach's principleData conversionModule (mathematics)Scripting languageCodeRevision controlInstallation artCache (computing)Enterprise architectureInternet forumNegative numberThetafunktionCAN busIntegrated development environmentIterationMusical ensembleGreedy algorithmSoftwareNeuroinformatikCodePhysical systemWeb browserQuicksortSocket-SchnittstelleChainMereologyInstallation artWeb 2.0Roundness (object)Integrated development environment2 (number)Revision controlBookmark (World Wide Web)Mobile WebLevel (video gaming)Regular graphDemo (music)WebsiteVirtual realityCopyright infringementThermal conductivitySpeech synthesisSource codeOperating systemFile systemCache (computing)CompilerMultiplication signExtension (kinesiology)VirtualizationInformation securityQR codeComputerMoment (mathematics)Scripting languageRight angleComplex (psychology)Graph coloringGodPointer (computer programming)PlastikkarteProjective planeUniverse (mathematics)XMLProgram flowchartComputer animation
20:46
Data typeScatteringComa BerenicesElement (mathematics)Function (mathematics)AreaFood energyoutputSet (mathematics)Computer filePoint (geometry)Translation (relic)Web pageLibrary (computing)Copyright infringementMoment (mathematics)Integrated development environmentStructural loadoutputScripting languageCodeType theoryRevision controlWeb 2.0Computer animation
22:31
Formal languageRun time (program lifecycle phase)WaveMultiplication signObject modelRevision controlEvent horizonScripting languageQuery languageFunctional (mathematics)Interface (computing)Object (grammar)Proxy serverWeb browserPoint (geometry)TouchscreenSemiconductor memoryNeuroinformatikElement (mathematics)Internet forumRepresentation (politics)Computing platformComputer animation
25:44
Web browserBoom (sailing)QR codeObject (grammar)Proxy serverVideoconferencingCodeElement (mathematics)Computer animation
26:43
Group actionDigital photographyMultiplication signBoom (sailing)Digital photographyComputer animationLecture/Conference
27:19
Covering spaceComa BerenicesPrime idealPoint (geometry)Internet der DingeEaster egg <Programm>Data miningMoving averageRoboticsMereologyStudent's t-testNeuroinformatikDisk read-and-write headDigital photographyWeb browserOvalRight angleScripting languageLecture/ConferenceXMLComputer animationSoftware
29:03
StatisticsSource codeDeterminismOvalInternet der DingeRoboticsGoodness of fitQuicksortWeb browserBlock (periodic table)Loop (music)InfinityNeuroinformatikThread (computing)Scripting languageCodeWeb pageWeb 2.0InternetworkingSerial portComputer animation
30:30
Food energyPresentation of a groupComa BerenicesMathematical singularityThread (computing)Graphical user interfaceWeb browserGraphics processing unitMobile appWeb browserComputing platformMobile appWritingScripting languageThread (computing)SurfaceWeb 2.0Level (video gaming)LaptopRevision controlLatent heatWeightOpen sourceSource codeVideoconferencingTurtle graphicsTelecommunicationProjective planeComputer fileCodeConfiguration spaceSocial classDebuggerBlock (periodic table)QR codeInterprozesskommunikationInterpreter (computing)SynchronizationGraphical user interfaceMessage passingData conversionModule (mathematics)Proxy serverQuicksortWeb pageDemo (music)NeuroinformatikProcess (computing)TouchscreenFitness functionTrailBefehlsprozessoroutputSoftware maintenanceType theorySystem administratorSoftware frameworkOpen setVector potentialComputer animationMeeting/Interview
37:02
Mobile appFormal languageFunctional (mathematics)Normal (geometry)VideoconferencingSystem callSlide ruleLecture/ConferenceMeeting/Interview
37:55
Functional (mathematics)Traffic reportingFluid staticsType theoryWeb browserLecture/ConferenceMeeting/Interview
38:36
Coma BerenicesNeuroinformatikImplementationWeb browserLevel (video gaming)SoftwareMultiplication signFunctional (mathematics)Mobile appScripting languageRevision controlSoftware testingLimit (category theory)Lecture/Conference
40:05
Mobile appTurtle graphicsScripting languageWeb browserProxy serverQuicksortConnected spaceChord (peer-to-peer)DatabaseCodeContext awarenessLibrary (computing)Module (mathematics)Software testingSpacetimeProcess (computing)MereologyWebsiteSocket-SchnittstelleWeb 2.0Lecture/Conference
41:59
Scripting languageSoftware frameworkUnit testingSoftware testingWeb pageWeb browserFunctional (mathematics)Speech synthesisMultiplication signAbsolute valueLecture/ConferenceMeeting/Interview
42:42
Open sourceSoftware frameworkMobile appWebsiteSoftware testingShared memorySoftware maintenanceComa BerenicesLecture/Conference
43:20
PiStreaming mediaScripting languageRight angleServer (computing)Multiplication signLecture/ConferenceComputer animation
Transcript: English(auto-generated)
00:04
Perfect. That's voice recognition for you. So thank you, EuroPython, for having me. So I'm going to be talking about PyScript and the magic of Python in the browser. This talk was actually proposed by my friend and colleague, Fabio, he's a colleague of
00:23
mine at Anaconda, he's the creator of PyScript. He's also a very special person. He's a former EuroPython chair and is now actually a EuroPython fellow. And from the photo, he's a sort of smoking hot photogenic sort of a gentleman as well, as you can see from the sort of Zoolander look that he's giving us here.
00:42
But sadly, he's not here for complicated reasons. So hence, you have me instead giving this talk. So this is me. I'm actually a Tuba player. And... Thank you. You've not actually heard me play.
01:02
And I used to be a teacher as well before becoming a coder as well. And I'm a principal engineer on the PyScript team at Anaconda. So PyScript. I better explain how Anaconda and PyScript are linked before we go any further.
01:22
So PyScript is an open source project. So please come join us and contribute and play around and do all the things that we do as a wonderful open source community. But PyScript was announced by Peter Wang, our CEO, just over a year ago. And Anaconda have been supporting this open source, this nascent open source project
01:43
of PyScript. So we wondered... We needed a logo. And rabbits, as you'll see, make several appearances in this talk. But we have a wabbit. I call it the Wasm wabbit, as you'll see. But our wonderful designer Katie went berserk with the bunnies.
02:03
And so we have lots of bunnies in our PyScript talk. I think it's because the way she designed the original logo was like a P, like a speech bubble. And then there was a kind of a Y that looked like bunny ears as well. So anyway. Anyway, in this talk, what are we going to cover? We're going to cover how exactly does PyScript work?
02:21
What exactly do you as Pythonistas get in the browser? And what exactly can you do with it? So those are the three sorts of core questions. So we'll just get straight on. So what is PyScript? It's a platform in the browser. So if the white box is the browser, what's inside that?
02:41
Well, at the very bottom, you have Python interpreters compiled to WebAssembly. Now WebAssembly is an instruction set for a virtualized sort of CPU. So WebAssembly and Wasm mean the same thing. Wasm's just a sort of shortening of it.
03:00
And as we'll learn in this talk, what you get is an ability to be able to compile C and C++ code to the WebAssembly target and then run that in your browser. Now CPython, the clue is in the name, is written in C, and so is MicroPython as
03:22
well. So we can compile these to WebAssembly and we can start making use of them. Now on top of that is PyScript. So PyScript is a platform that sits on top of these Python interpreters. And we, as we're going to show you in a second, try and make it as easy as possible for you to actually be able to start writing Python as quickly as possible.
03:42
So we try and take care of the boilerplate and sort of all the other sorts of bureaucratic things that we do to get Pydied, which is CPython, into the browser and MicroPython. And then on top of that is your code or frameworks that you might have written as well. So you can do useful stuff.
04:01
And so PyScript makes it simple to get Python in the browser, and that's really it. So how does PyScript work? I'm going to give you a numpty example. This is an actual PyScript, as you'll see, but what you'll see is perhaps a simplified version of why we perhaps need PyScript. So we're looking at some HTML here.
04:22
HTML is the language of the web. And if you look, there is a PyScript tag with some Python embedded in it, print hello world. And for me to make that work, if you look in the head tag of the HTML, you'll see that there is a script tag. We're going to be saying the word tag an awful lot this presentation.
04:42
There is a script tag that has a source of PyScript.js, and that's really all you need to reference, and then you get Python in the browser. So let's have a look at that working. Let's see if this works for me. Hello world. There you go. Woohoo!
05:04
Well, you've not seen the implementation yet. So how does this work? So what's in the PyScript.js file that I was referencing? And remember, this is a dumbed-down example, just so that for the purposes of pedagogy, I can sort of show you the sorts of tricks that we have to do.
05:23
So to create the PyScript element, I need to create a class in JavaScript, because JavaScript is the, you know, it's a JavaScript file. And there is a base class called HTML element, and I'm basically declaring I want a new PyScript element, HTML element.
05:40
And then what I do is I override something called connected callback, which is called whenever the browser encounters this tag in the DOM. And what do I do? Well, I grab the code, the print hello world from inside the tag, and then I instantiate
06:03
my Python interpreter, and then I interpret the code and emit it out to the I put the answer as the textual content of the PyScript tag. And then right at the very end, I call a built-in function, custom elements.define, and this
06:24
is where I'm saying, well, you see PyScript, Py-Script, I want that to be handled by the PyScript class, okay? Oh, my. So clearly, that's not how we do PyScript, because you can't do a lot with that version of Python. That's Nicholas's Python.
06:41
So what we're going to do is actually add a Python interpreter, and I'm going to call out Damien George, who's actually in Melbourne, Australia at the moment, but Damien has created a version of Python called MicroPython, which is designed to run in highly constrained environments like microcontrollers. Now little did he know that you could compile this to WebAssembly, and all of a sudden
07:03
people are very interested in using MicroPython for that particular context. So what we're going to do is take MicroPython as a very simple and quick and small Python interpreter and add this to our nascent PyScript, as it were. All told, though, just some interesting facts about MicroPython.
07:22
Actual MicroPython is about 170K to download, which is smaller than most images on a website, if you think about it, okay? For that size, you get a pretty comprehensive Python interpreter. It's small, it's fast, and this is what we want to use. So here we go. This is some code that I'm going to run, and if I can find my pointer, there we go.
07:49
If I click view, there we go. Hello world from MicroPython, and if I view source, just so that you can see that we do actually have some Python that we're interpreting there.
08:02
So hello world from MicroPython. So how does that work? Well, back in the land of JavaScript, back in the HTML-derived class, I grabbed the textual content of the element, which is the Python file, and then I set it to blank.
08:26
And then I rebind this to self. Those of you who use JavaScript might be smiling. JavaScript has a complicated relationship with the notion of whatever this keyword might refer to. Okay? So I'm making sure that I've got a handle on that.
08:43
And then what I'm doing is I am creating a callback function that listens to an event called MicroPython print, and all that call function does is append whatever data is being passed in via that event to the inner text of the element, okay?
09:07
Now MicroPython-print is an event that MicroPython itself emits whenever it prints anything to standard out. Okay? So that's how we get stuff from inside the interpreter, outside into the world of
09:22
the browser. And then, when this code is evaluated, at this moment in the life cycle of the page, we will have available to us an MPJS do this string, and we pass in the code, because
09:41
we've got everything sort of set up, okay? That's part one. Part two is actually we have to get MicroPython into the web page, okay? So what do I do? Well, I manually, in my code, create a new script element. Then I reference the MicroPython.js file as the source of that script element.
10:03
Now MicroPython.js is an asset that is created when we compile MicroPython into WebAssembly, and it does all the boilerplate of setting up the interpreter for us, okay? And then this new script element that I've created, I create a new callback function
10:21
that handles the onload, which is called when MicroPython has been downloaded and is sort of running, okay? And within that event handler, what do I do? Well, it's a bunch of stuff, but lines 33 and 34 are important, because that's where I actually instantiate the MicroPython interpreter and give it the huge memory size of one
10:43
megabyte to work with, which is massive for MicroPython, okay? What you need to know is that MicroPython has dynamic memory growth as well, so it will grow now to fit whatever strange objects you try and manipulate with it. And then remember how I told the browser about the PyScript tag and to use this class?
11:05
Now that I know that we have Python ready in the browser, I use custom elements dot define PyScript and use the PyScript class that I defined above in part one, okay? Are you paying attention? This is JavaScript. We're going all over the place here.
11:23
And at that point, the browser will pick up on the PyScript tags and start to do its stuff as well. But we're not finished, because I need to get a reference to the head tag in the document and then insert the script tag that I've just created into the head tag,
11:42
and only when I do that does all of this kind of stuff unravel and eventually we get MicroPython in the browser, okay? So this is kind of stand on one leg, stick your finger in your ear, whistle God save the queen, and you get a Python interpreter in the browser, okay?
12:00
So PyScript doesn't work like this, okay? But I hope that you can see some of the more convoluted things that we have to do to actually get Python in the browser is simply for you between two PyScript tags, okay? But so, yeah, quite.
12:21
It's quite a process. So why would you want to do this? So this is a question that Fabio likes to ask. You want to share this really complicated Python application with grandma, okay? Now, grandma, nothing against grandmas, but grandma is a placeholder for a non-technical person. How would you do that?
12:41
How confident would you be phoning up your grandma and going, I've got this print hello world app that I want to test out on you, and she knows nothing about computers. How would you do that? How confident would you be to do that? Well, okay. All the things that we usually say, like, okay, well, first download Python, and then
13:04
you need to open your terminal. What's the terminal, darling? Oh, no, never mind, hang on. Now pip install this thing. What's pip? Blah, blah, blah, blah. This is complicated stuff, okay? So if we can just say, why don't you go to this website, and in there is your
13:23
Python app, your print hello world Python app. That allows people to get to your code a lot quicker and in a lot less fraught way as, you know, download Python, pip install the thing, conda install the other thing, blah, blah, blah, blah, blah, blah, blah, okay? So PyScript is just a platform for Python in the browser, and Python runs anywhere
13:43
now there is a browser. So this is a short video. This is PyScript.com, which Anna Conda has built, and it's a very simple IDE for, well, editing Python in a browser. And you can run Python in the browser.
14:00
And Antonio, my colleague, Antonio Cuney, who's famous for PyPy, who's down there, is a great artist. You know, Canaletto, Leonardo, Michelangelo, and now we can say Antonio, because this is his version of the PyScript rabbit. And now it makes an appearance whenever we do demos and things like that.
14:23
So there's Antonio's rabbit in a regular web browser, okay? Now, here's the same code running on a browser on my rather old mobile phone, okay? Now, all of a sudden, we now have Python running in a browser on a mobile phone. Now, if you are a child at school and you are learning to code, your primary computing
14:41
device is one of these, okay? And you can now get your code running on your mobile phone. But that's not all. You can actually run it on any appliance that has a browser in it. I kid you not.
15:01
Although Fabio said you're going to have a big problem expensing that expense through finance anaconda. But imagine, if you will, what running Python in the browser now gives you. A chance to troll a beloved colleague on stage at EuroPython using a silly car.
15:25
But imagine what you could do, okay? We are bringing the world of the web in all its colorful glory, and the world of Python in all its colorful complexity and glory, and we're putting them together, and we're asking, okay, if they had a baby, what would that look like?
15:42
And our answer is, it kind of looks like PyScript. Now, you can yourself run this PyScript bunny on your mobile phone, and let's hope that the conference Wi-Fi is working. But just QR code the thing, there's a tiny URL that will redirect you to the source code on PyScript.com.
16:01
And if you look at the bottom right, you can start to view source, and it will take you to an IDE that will let you start to edit that as well. So how is Python able to run on the browser? What about the kind of operating system layer, because it's just a browser, right? How does that work? I can see people still with their phones up, so I'm just going to pause here for
16:21
three seconds, two seconds, one second. Somebody's got the bunny running. I can see it already. Just hold it up. It's going to be like a rock concert now. Look at that. Antonio, this is a moment. Please give Antonio a round of applause. Stand up. Stand up.
16:45
No, no, no, no. He'll sign them later. If you have a pen. So how is Python able to run in a browser when it doesn't have an operating system underneath?
17:00
Well, the answer, the simple hand-wavy answer is we use something called Emscripten, which is a sort of a part of the compiler tool chain that also allows us to abstract away things like a file system or sockets or all the other things that one might get from the operating system layer of things, and that is compiled so that when Python source
17:22
code asks for sort of system calls, there's an equivalent for the browser in there. So it's like libc or POSIX or the win32 layer, things like that, okay? So that's Emscripten. It's fast is what I need to say. So how do you create an environment in which you can run Python?
17:43
Now, this is a favorite subject for all of us, isn't it? Because some people use poetry, some people use pip, then there's virtual environments or there's conda or blah, blah, blah, blah. Well, what's the story here? Well, packaging with PyScript is mostly like Python. Actually, your browser tab is basically your virtual environment.
18:04
The browser is probably the best sandboxed computing environment in the universe, because let's face it, it's the most used piece of software. And we've had a lot of experience securing this particular sandbox so that nefarious people can't do nasty things, because we don't want them to be able to do that.
18:24
And the web world has spent 27, 28, maybe even 30 years, I'm trying to remember when Mosaic was first released, maybe even 30 years ago, gosh, I feel old, because I remember when that happened, I was at university. They've spent a lot of time and effort making sure that these are secure computing
18:41
environments, okay? So your browser tab is like your virtual environment, okay? And then we use a tool called MicroPip, which allows you to install packages from PyPI, and it just works. Except packaging with PyScript is mostly like packaging with Python, okay?
19:03
Those packages that have C extensions need to be compiled to WebAssembly. And HUD and ROMA and others involved in PyDyde, I'll come on to that in a second, have been making sure that we have some sort of a story so that when you upload packages to PyPI,
19:20
you can get it compiled to WebAssembly and it should work. Also, every time you open that new tab, you need to install the packages each time you navigate to that URL. Now there are subtle ways that we can use caching and things like that to speed things up, but we're still working on that sort of thing as well. And actually sometimes the browser isn't actually a friendly place for some of the popular
19:45
packages like requests, which works in a blocking way, whereas the browser works in a non-blocking way. Now there are ways of patching requests and things like that, but it's not just the simple story of import requests, request.get some URL, okay? Work is ongoing with these sorts of puzzles.
20:05
So let's explore how you may go about using packages by exploring the R package that's published on PyPI. R does exactly what it says on the Timp. It's pirate speak for Python.
20:21
And the thing I like about it is that it has a serious code of conduct and a not so serious code of misconduct. So pirates are greedy, inconsiderate and respectful and so on and so forth. But I wrote R as a teaching project, okay? And so what I need to do is show you the code. And I've lost my pointer again.
20:42
So let's explore what happens. So if I go and visit the R website that I built with PyScript, and here's hoping that it works. Loading conference Wi-Fi. Loading conference Wi-Fi. Here we go.
21:00
So this is an older version of PyScript. And we're downloading PyDyde, which is the version of Python that we're using. It's probably downloading loads of Antonio's rabbits at the moment, which is why we can't see this happening. Oh, come on, conference Wi-Fi. Anyway, the important thing is that you get the web page,
21:23
you type some English in here, and then you click the translate button. Here we go. So if I type in here, hello, you're a Python, full stop. I hope this works. Let's find out. And then click the translate button.
21:42
Oi, you're a Python. I hope this works. Splice the main brace, let's find out. So we get some pirate speak back, okay? And well, how does that work in Python? So if I go view the code on PyScript.com, we can see I import R, and then I grab the input text.
22:05
I pass it to the R library, okay, to get a translation of what the English text is, and just set the inner text to that. But just so that I can set up my environment, which is the point I'm trying to make here. I have a toml file, and inside that, I have a name of a package on PyPI.
22:26
And in the background, it just works. It grabs the thing that you need, okay? Nice and simple. The black pearl. So what runtimes do we have available in PyScript?
22:41
Well, we have Pyodite, and this is a version of CPython that Hood and Roman, if you're here, could you just wave? He's not here. He said he would be here. Well, never mind. Hood and Roman, you'll see them around. They have done a huge amount of work on Pyodite to get CPython working
23:03
really effectively and efficiently in the browser, okay? We also have MicroPython. Damien has done some magnificent work very recently on getting us MicroPython in the browser. But at the heart of the next version of PyScript is something we're calling PolyScript.
23:22
I also need to call out my colleague, Andrea, who's done some incredible work on getting this to work. Now, if you can have more than one runtime, perhaps we could have Lua to this. We've also had Ruby working as well. So you can now start to get all sorts of interesting scripting languages
23:41
into the browser. And we're just trying to help make it easier. But clearly, this is PyScript, and we are focusing on Python in the browser. So the two platforms that we say that we support are Pyodite and MicroPython, although we have been experimenting with Lua and Ruby, okay? So we've got Python, a Python, in the browser.
24:04
And now we want to use Python to interact with the browser. How does Python get to the DOM, the document object model, the representation in the computer's memory of what's being displayed on the screen that we write as HTML, okay?
24:21
Well, it's very simple. You just import JS. And the JS object points, is a proxy, to the global this that you get in the browser. And off that, you actually get the document object and all the other APIs that you have available to you in the browser
24:40
just from JS object that you import there. This is a FFI, a foreign function interface, that's been written in Pyodite. That was some fantastic work that Hud did, and Damien has used the same API, although it's a rewritten version for MicroPython, to give us the same capability, okay? So import this.
25:01
So what can you do? Well, consider this very simple example of HTML, okay? I have a button with an ID of ClickMe. So what does that look like now in PyScript? Well, from JS, I import the document, okay? I define a handler function in Python, okay? I do some stuff where I create a new span element,
25:23
I insert a mouse into it, and then I append it to the body of the document, and then I just use document.querySelector to get me the button that I've just created, and then I use the button reference to add the event listener that I've just defined in Python. So what does that look like?
25:43
Where are we? ClickMe. There we go. Boom, boom, boom, boom, boom, boom, boom, boom, boom, boom. Now, did you see how quickly that loaded? That was MicroPython running in the background, okay? And that, as you know, is running on conference Wi-Fi, so if it works quickly there,
26:01
it's going to work quickly anywhere really, okay? So we have also full access to all of the browser's APIs. That's not just interfacing with the DOM and manipulating the DOM, okay? So we can do other things. So consider this. I have a button and a video element, okay?
26:23
And in this fragment of Python code, okay, I do all the things that I might normally do in JavaScript, but do it in Python, because we're just using proxy objects from the JavaScript world from Python, okay? Here's the QR code that you really need to see, okay?
26:43
If we go look at it, let's see if I can make this work. Boom, boom, boom, very fast startup time, thanks to MicroPython. I've lost my thing again. Let's see, start camera. Okay, there I am. And let me just, mm-mm-mm, take a photo. Now I need to look gorgeous here.
27:04
Okay, good, and then I can, oh, gosh, then I can download the photo and do whatever I need to do with it, et cetera, et cetera. But this is all written in Python, okay? And it started like that.
27:24
My point being is that you get full access to all the capabilities of the browser from Python. Now, this example is based on some work by a wonderful friend of mine called Professor Chris Rogers at Tufts University. Now, Chris, Chris is the, well, they're all grinning,
27:43
the insanely grinning gentleman on your right-hand side, halfway up. That's Chris, and there's Ethan and Jen as well. And some photos of some of the stuff that they do at Tufts. He's the head of the CEO of the Center for Engineering, Education, and Outreach. And for perhaps the last 25 to 30 years, Chris and
28:03
his colleagues have been researching and experimenting how do we teach engineering and computing and robotics and all of those really cool subjects, okay? Whenever I go and visit him in Boston, it's like, I don't know, It's like a child in a sweet shop, but for nerds, because there's like Lego,
28:22
there's a robot over here, there's some Python running, some blah, blah, blah, blah, blah, it's wonderful, it's really great. And he's a very enthusiastic, well, all of them are very enthusiastic teachers, and their students are wonderful as well, okay? Now, part of their curriculum is using Internet of Things.
28:40
So this is something that they built with PyScript. There's pyscript.com, plug in an egg, press a button, the Lego thing starts, and you have an automated killer Easter egg robot thing for decorating Easter eggs. And this was being used at the White House's annual Easter egg roll
29:04
that Ethan went to, and he had a whole bunch of kids lining up to use MicroPython running on the Lego, and well, Python's everywhere really in that example as well, so I really love that. But it means that because we can use the browser's USB
29:24
serial API, we can get access to the Internet of Things, we can get access to Bluetooth things, and all the other sorts of good stuff that we have, okay? So, okay, that's the source code for the egg roller, should you be interested. But of course, you need a Lego robot and an egg, actually,
29:43
and a felt tip pen to make it work, okay? So talking of things that spin, have you ever seen this on a web page? I'm sure you have. When you see that kind of like rotating beach ball of doom, which is telling you your computer is busy, what you're actually doing is
30:02
you're blocking the main thread on the browser, okay? You're blocking the piece of code that is constantly updating what's going on in the viewport that you can see in your browser, okay? And you don't want to do that, okay? If you have an infinite loop in JavaScript in the main thread,
30:21
you're just gonna block, okay? And it's the same with PyScript and Python, okay? So please don't block the main thread, okay? So what do we do? There is a solution. Good, it all fits on the screen. In the world of the web, there is a concept called a web worker.
30:42
Now, the equivalent, I guess, is something like having a new subprocess or starting new subprocesses on your web page, okay? And so web workers are sort of similar to separate processes running in the background of your web page. So you put all your expensive computation on there
31:00
whilst keeping the main thread unblocked, okay? PyScript's next version supports this. I've been using this, and we'll see a demo soon. And it even has a simple API for proxying from the web worker back to the DOM on the main thread. So you can start to do inter-process communication and manipulate what's going on in the browser.
31:21
So how do they work? Well, there's a sort of a cross worker proxy between the main thread and the worker, and this X worker proxy kind of is helping with the message passing, the conversation. I was trying to think, how do you represent a conversation?
31:41
And I could only think of something like WhatsApp to do that. So essentially, we've got a kind of a conversation going on, okay? And we have transparent message passing done in a way that will pause the worker allowing for synchronous Python code whilst the main thread remains unblocked, which is an important thing that you need to be able to do.
32:04
Because of course, when you type name equals input, what is your name? The Python interpreter on your desktop blocks, and you need to be able to have the same capability in the browser as well. Okay, it also allows us to have the Python debugger, which is another thing Antonio's famous for.
32:21
It's bunnies, PyPy, and debuggers, okay? So what does that look like in Python? Well, on the main thread, I just import an X worker, a reference to the X worker class. And then, I don't know, I'm gonna spin up 12 web workers. And I just say, I want you to run pom pom.py using that particular
32:41
configuration file so that we know what packages you've got. And I want you to run that with MicroPython, okay? And on the worker end of things, we've got the turtle module, which is doing a whole bunch of turtle-y things, okay? The hint is in the name, pom pom. Okay, that will draw us some pom poms. And then, underneath, we're doing some communication
33:03
back to the main thread to say, you know what? The stuff that I'm using, I'm generating from the turtle module, I want you to insert that into the DOM. So actually, what we get to see is something that looks like this. Lots of pom poms. There we go, turtles all the way down.
33:22
Okay, so this is a video. I'm not gonna try and attempt this without the aid of a safety net in front of EuroPython with conference Wi-Fi, but there we go. Anyway, you can do this. It's a good example. And here's the QR code. I can see everybody reaching for your mobile phone.
33:42
Click, click, click, click, okay? Because Firefox hasn't caught up with some of the nascent web worker specifications, this only works on recent versions of Chrome. And it may melt your laptop, okay? We just had a talk from Sophie.
34:01
This is a great way of getting it to that rocket engine level of heat, okay? Cuz the browser is actually doing an awful lot in subprocesses there. So it's very early days, and we're only just scratching the surface of PyScript's potential. Both for the Python world and the world of the browser. And PyScript is what you get if the web and Python had a baby.
34:26
We've had the baby, and now it needs nurturing, which is kind of where you lot come in as well, okay? So please, come and talk to me, come and talk to my Anaconda colleagues as well, look at the source code, contribute to the source code.
34:40
Write goofy things on PyScript.com, or maybe use PyScript to build an app that runs on a mobile phone. That would be rather interesting to see what you build, okay? So some final thoughts before I end. PyScript is a platform, so you build things on top of it. PyScript as a platform looks after a whole bunch of other stuff
35:03
underneath it. It runs everywhere a browser runs, and we've seen that's pretty much everywhere these days. And you write your code and your frameworks on top of PyScript. It's open source, so please come and play.
35:22
And as Peter likes to say, it's for the 99%, it's not just for coders. One of the, this is why I joined the project really. One of the big motivations here is that we try and make programming an empowering experience, rather than, okay grandma, download Python, now pip install the thing, now do the da-da-da-da-da.
35:44
PyScript, if you're a school teacher, is a real blessing, because you don't have to bother your sysadmin to try and get Python installed everywhere. You can just tell kids to point their browser at a thing, and PyScript just works. It's a great teaching tool, okay? These are some of the PyScript maintainers.
36:01
It's a lovely bunch of people, so we're friendly, come say hi. And stay here in this room for the following talks. Running Python packages in the browser with Pyodide. That's Roman, I don't know if he's here. But Pyodide, like I said, is the C Python version that we use in PyScript.
36:20
So he's immediately after this talk. That's gonna be a really interesting talk. And then we have How to Draw Bunny Rabbits by Antonio, sorry, the CPU in your browser, WebAssembly demystified by Antonio. He's immediately after Roman. And then I have my friend and colleague who is somewhere, he's over there,
36:40
Dr. Russell Keith-McGee, all the way from Perth, Australia, is gonna be talking about packaging Python apps with Briefcase, which is gonna be a very fascinating journey, I can tell you. So please say hello in the corridor track, and in the sprints, and all the other places that we are, and that's it. Any questions?
37:09
Thank you, Nicholas. You're welcome. So there was one question in Discord, and as I read this out, there's microphones here. So you may line up by the microphones and ask your question in person.
37:20
So the very first one is, will you be sharing the slides for this? Or you read it? Excellent. Okay, please. We asked a little question. In one of the apps, we saw there was a callback for a picture, and a callback for video. One was async, and the other was a normal Python function.
37:43
When do we use asynchronous functions? And when do we use normal functions for callbacks in a Python script? Okay, so thank you. That's a very good question. So JavaScript is an asynchronous language. You await things in JavaScript. Clearly you can't await things in a regular function.
38:01
You have to await things in an async function. So you just define your Python function that awaits the JavaScript thing in an async way, and it just works. Yep, next. Hello, Nicholas. Thank you so much for your report, I guess. I have a question.
38:21
Does the PyScript support some kind of a type hinting, or is there any possibility to integrate it with some static linters or something around that? Okay, so what you get is Python in the browser.
38:42
So if Python can do it, and Pydide is CPython, then you can do it in PyScript. That's it. Okay, nice. Thank you. Cool. You're welcome. Next question. Thank you for your talk as well. You're welcome.
39:00
Did you make timing tests, so same functionality for JavaScript and Python, and what's the ratio for the timing? That's a really good question, and the answer is, I don't know. Because if you imagine software is developed in three stages famously. I can't remember who said this.
39:20
There's the first stage, which is, just make it work. And the second stage is, just make it work properly. And the third stage is, if and only if you need it, now make it work efficiently. And I think where we're at is stage two. With the next version of PyScript, we've kind of ironed out all the kinks and the kind of implementation details.
39:40
But does it work efficiently will absolutely require all the things that you've just said about measuring performance and comparing where the computation might take place in the world of JavaScript or Python or whatever. So we're getting there is, I guess, the answer. So thank you for that. Thank you. We have a gentleman who's been stood at the back.
40:01
Thank you. Thank you. So what are the limitations of PyScript? Do you know examples of the apps that cannot be done with PyScript? Yes, so funnily enough, Turtle can't be done with PyScript because it requires TKEnter. And that would be weird, running TKEnter in a browser, OK?
40:21
So what you saw was a bodge that I hacked together from somebody else's code I found on blah, blah, blah, blah, you know, the typical sort of thing. So there are examples of modules in the standard library that clearly don't make sense in the context of the browser. So TKEnter is in the back. So for example, what about connecting to the database from PyScript?
40:44
OK, that's a really good question. So usually what you do is you connect the database through ports, OK? Now, because the browser doesn't give you ports, you have to do either web sockets or an HTTP connection.
41:02
Then you can't directly connect. So you usually have some sort of proxy in between. And that's something that we're going to be adding to the PyScript.com website. So there's a way to allow you to proxy to other things that you might need to connect to, like third-party APIs or whatever else it is that you can connect to. So it will be in JavaScript?
41:20
I don't know. I'm not that part of the team. OK, and do you have any idea how to store, I don't know, secrets for external API? Again, that's the proxy's job. Because as you know, if it's in the context of the browser, then the user or something in the user space will be at the backside. OK, do you have any examples of ready proxy
41:41
that we can check the code? Not right with me. I've, you know. OK. This is something you should ask on our Discord channel. My colleagues will get back to you. Thank you. Before we take another question from the front, there's one question on Discord. Did you try running PyTest and PyScript? I imagine it could be useful.
42:01
Yes. I'm working on a framework that sits on top of PyScript. And the unit tests are refresh the page, and PyTest works. And you just see what you would normally see in PyTest. And we will have time to take one or two more questions. Please. Hi, thank you for the inspiring speech, first of all. I have a question. Could we run Python functions directly from JavaScript?
42:24
Let's say we have a hello world function in a Python script. Can we execute it from a JavaScript directly? Absolutely. Absolutely. Yes. So I've been talking about Python in the browser. But you could go from the browser and getting into Python as well. You can absolutely do. Thank you.
42:41
And our final question. Hi, thanks for the amazing work. I have a question on maintenance on PyScript.com. Because I would like to share lots of data apps on PyScript.com for a framework, an open source framework. But right now, I can't maintain that when we update our framework and so on. If I have a lot of apps, how can I efficiently
43:02
work with that automating stuff, testing stuff across a lot of data apps? OK. So the simple answer is you're talking to the wrong person. Because I'm on the open source team. And we have a dot com team who manage the features related to the website.
43:21
But they're probably watching the live stream right now. And Martin and Ted and Fabio are probably thinking about this already. And it will be addressed. My advice, if you have questions about, can PyScript do this? Are you going to add this to PyScript.com? Blah, blah, blah, blah. Is to go onto the Discord server and just ask. And we're all on there.
43:40
And the right person from the right team will be able to answer your question. Fantastic. And that is all the time we have for questions. Thank you once again so much, Nicholas. Thank you. Thank you very much. Thank you for listening. OK.