So let's do some history here, so you can see that whilst this idea seems crazy it also fills me with some delight and charm. So I have been a front end developer for some wow -- 15 years, I have seen all the trends and ridden the wave of all sorts! I mean do you remember GSS? Yep JavaScript polyfills for CSS, I mean who wouldn't want a grid in good ol` JS! That was 2014 but now it's 2022 and we have Python in the Browser! and my fellow developers I love Python! Its a match made in heaven!
Here is some context on GSS https://www.sitepoint.com/introducing-gss-grid-style-sheets/
So how about we give this a go with a simple hello world shall we.
First off lets create a folder call pyscript and within that folder create a index.html.
Ok lets have a basic HTML layout
`
<!DOCTYPE html
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
`
That's perfect! Just not formatted! and there is a reason for that which I will get to.
Ok so with our template lets add a head section and pop a couple of CDN links
<pre><code>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
</pre></code>
And now we have a simple tag we can use which is , which allows us to write some python and basically run it!
So let's remove the heading and paragraph tag and replace it with the following:
`
<py-script>
def helloworld():
welcome = False
if welcome:
print('Hello World')
else:
print('Not today please')
helloworld()
</py-script>
`
So this is the reason we do not format the code and that is purely down the fact it seems if you try and format it the page will fail to load through indentation errors.
So our final file should look like so:
`
<!Doctype html>
<head>
<link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" />
<script defer src="https://pyscript.net/alpha/pyscript.js"></script>
</head>
<body>
<py-script>
def helloworld():
welcome = False
if welcome:
print('Hello World')
else:
print('Not today please')
helloworld()
</py-script>
</body>
</html>
`
And if you run it in the browser you will be greeted with our else message and python is running. Now it does take some time to render and would work well in a dashboard setting but I wouldn't like to use it in a website environment as it would take a while to load the page to the user.
Also if we look at the console we have a full output as to what's going on and if you do get errors you get a full break down of what's going on there.
So anyway yeah its fun, its delightful but where would I use it? I'm not sure I would...
Edit, please excuse the code examples and the rendering of the HTML code blocks, trying to escape HTML in markdown is a real pain.
Top comments (1)
Python in the browser is a great concept though.