11

Is it currently possible to have Python snippets on Stack Overflow?

Python is getting increasingly popular and is also currently the most tagged language in Stack Overflow. It has got 1177 questions asked just today at 9:30!

I did google it, and I found this and this post, but it was asked four years ago. Surely, technology has updated since then? I am a relatively recent coder, but I read in the post and I have heard in other places that it is possible using Skulpt.

8
  • 1
    It's already possible with DataCamp in Stack Snippets, to a limited extent stackoverflow.com/a/53422775 but I'm doubtful backend languages are that suitable for being made runnable on SO - it's possible with a lot of work, but it's pretty complicated. Pasting the code and linking to someplace like ideone.com might be better Commented Sep 4, 2020 at 4:19
  • 32
    Keep in mind that the major difference between JS snippets and other languages is that JS can be executed online without implementing or otherwise downloading an entire Python interpreter. If we can't have basic MathJAX over size constraints, I highly doubt this will be implemented. Commented Sep 4, 2020 at 5:38
  • 4
    You should also keep in mind how many different requirements can be required to run a python script and SO (or any other website) shouldn't be expected to keep them all on hand so that scripts can be run in a post.
    – Joe W
    Commented Sep 4, 2020 at 18:41
  • 6
    "Technology" isn't really the problem here, it's domain. Most JS can be run in a browser, node.js, cannot be because its domain is more than just web. It would be like asking to be able to run iOS code on a non-apple computer. It can be done, but the tool chain is ridiculous. Allowing snippets is much easier (although still not without security concerns) and maintaining it is easy as well because no update to JS would ever make JS unrunnable on the web.
    – zero298
    Commented Sep 5, 2020 at 0:50
  • If the purpose of a runnable snippet is so that a reader can click "play" and see the output, what is the benefit of this over just requiring people to include the output in their post as static text? With Javascript snippets at least the "input" and "output" might involve GUI interaction and DOM manipulation, but Python code cannot naturally accept input or produce output via a browser. Would runnable Python snippets also require a terminal emulator to be embedded in the post?
    – kaya3
    Commented Nov 30, 2021 at 17:53
  • 2
    Could you please edit to clarify what new information this feature request brings over existing once? Something like recommending client-side Python VM... that was not suggested before? Commented Jan 20, 2022 at 5:31
  • @AlexeiLevenkov I don't have any suggestions for how the implementation should be done. What I have that add more information to the other requests are the reasons for why the snippet should be done for Python language, which I stated in the questions in total 3 reasons, all of which has legit references. I only suggest that it should be done, but I do not concern on how it is done.
    – holydragon
    Commented Jan 20, 2022 at 5:59
  • 6
    Python relies a lot on third-party packages, has many use-cases that require using OS resources like files, sockets, and so on, and often has implementation/compiler/tooling specific questions. These are usually things a "runnable snippet" cannot support at all, or at least not well. How many Q&As would benefit from runnable snippets at all? For every question improved, how many will be worse because the author picked the wrong code kind of code/snippet or wasted time before figuring out what works? Commented Jan 20, 2022 at 6:36

4 Answers 4

20

This is not feasible.

Stack snippets run entirely in the browser. You can't run Python in everyone's browser, not the CPython (main) implementation.

Python is a very, very rich ecosystem, with multiple implementations, and while there are implementations that run in a browser, these are far from complete nor can they run many of the libraries that make Python so popular, such as NumPy and Pandas for data science *), or Flask, Django or Quart for web applications, or Tkinter, Qt and GTK for GUIs.

Nor do I feel it is necessary; I have been answering Python questions for over 12 years on this site without the need for snippets. It's not like Python is regularly used to create dynamic HTML and style output, the way JavaScript is, for example.


*) Yes, Pyodide can run much of the data science stable of libraries, but has no working threads, sockets or multiprocessing support, which in my view is a severe limitation. It is also resource heavy, something the Stack Overflow team has tried to avoid in the past.

13

I completely agree with the answer of Martijn Pieters.

Stack snippets run entirely in the browser. You can't run Python in everyone's browser, not the CPython (main) implementation.

Sometimes we need to demonstrate some code that does not require OS-bound kinds of stuff or drivers. The PyScript with help of Pyodide gives the ability to run Python code in a browser.

PyScript is a meta project that aims to combine multiple open technologies into a framework that allows users to create sophisticated browser applications with Python. It integrates seamlessly with the way the DOM works in the browser and allows users to add Python logic in a way that feels natural both to web and Python developers.

Yes, it cannot run threads, processes, or sockets and has limitations, but it can execute such third-party libraries as Beautiful Soup, Bokeh, Matplotlib, Natural Language Toolkit (NLTK), NumPy, Pandas, Pillow, SciPy, SQLAlchemy, scikit-learn, etc.

Pyodide uses WebLoop as the main event loop so that we can execute asynchronous functions as well.

import asyncio
import numpy as np

async def func():
    for i in range(2, 7):
        await asyncio.sleep(.5)
        print(np.random.randint(i, size=10))

loop = asyncio.get_event_loop()
loop.run_until_complete(func())
<script src="https://cdn.jsdelivr.net/gh/pysnippet/pysnippet@latest/snippet.min.js"></script>

As you can see, it is enough to add the PySnippet CDN as an external library and run a Python snippet.

Also, note that I have used NumPy without installing it as the PySnippet has been made to solve the auto setup of initialization requirements for easy use.

1
  • If there are newlines in the output (which can happen for example if there are Python errors), the output is more readable if you add py-script{white-space:pre;} to the CSS. Commented Oct 17, 2022 at 16:06
-6

EDIT: I use Pyscript for the example (to make the example much simpler) - powered by Pyodide - "Python with the scientific stack, compiled to WebAssembly."

I hope Stack Overflow will enable Python as official code snippets soon, but currently if you using python with scientific stack (and not with gui) Pyodide can be used from Stack Snippets.

<!DOCTYPE html>
<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>
    # Python code here
    import random
    print("Generate random integers between 0 and 9 in python:", random.randint(1, 10), sep="\n") # SO: 3996904
</py-script>
</body>
</html>

5
  • What is "js playground"? A generic one? Or a particular one? Stack Snippets here on Stack Overflow? Can you elaborate? Commented Nov 30, 2021 at 12:15
  • 1
    Pyodide is nice, but would it be a net benefit for Stack Overflow? It supports one out of five Python releases (not counting older versions, PyPy and things like Cython), lacks some prominent libraries and while the scientific stack has many users, Python is used for a lot of other things – that often involve things the browser just cannot supply. For every code snippet improved by this, how many will be worse because the author picked the wrong code kind or wasted time before figuring out what works? Commented Nov 30, 2021 at 12:49
  • This snippet isn't working, it just shows me "out of memory" errors. Commented Nov 30, 2021 at 15:45
  • pyodide work with WebAssembly... so your webbrowser may not support it or your webbrowser not config enough memory for python dist caching
    – matan h
    Commented Nov 30, 2021 at 19:36
  • 4
    Pyodide can't run threads, multiprocessing or sockets. It's a great project, but those are three honking great limitations that would cut out a huge swathe of questions and answers in the Python ecosystem.
    – Martijn Pieters Mod
    Commented Jan 20, 2022 at 9:18
-6

As the answers above said, this is possible with Pyodide or pyscript, but pyodide doesn't provide an interface and pyscript is painfully slow and also doesn't provide a great editable live demo tool. This is why I built my own project on top of pyodide which lets you run editable python demos.

Check it out at PyPrez or below!

Run the javascript snippet below to see a runnable Python example:

import random

x = 5

if __name__=="__main__":
    print(f"my random number is {random.random()}")

    # now produce an error to debug
    print(x[2])
<script src="https://modularizer.github.io/pyprez/pyprez.min.js" theme="darcula"></script>

5
  • 2
    It took me a while to figure out that you have to click on the green arrow to run it. It would be more intuitive if you could fix it so that it runs automatically as soon as you click on "Run code snippet". Commented Oct 17, 2022 at 15:48
  • 1
    Thanks for the comment @DonaldDuck ! I've updated it now to automatically run the first time then you can click the red reload button to eidt it and then run again. It is still a bit slow the first time it loads... Commented Oct 19, 2022 at 1:18
  • 1
    Nice work! Another thing you can fix is that on my device it looks like this when it's done loading, so it's hard to see that it's done loading. Maybe you could fix so that it automatically scrolls down to show the results when it's done. Also for longer code snippets it might be useful to scroll down to "Loading..." while it's loading so that people can see directly that it's loading. Commented Oct 19, 2022 at 8:15
  • 1
    @DonaldDuck thanks for letting me know! I added in some logic to scroll to the bottom for now, although I'll probably work on trying to reserve more space so scrolling becomes unecessary. Note I also changed the src to point to a minified script and I allowed specifying Codemirror themes. I appreciate your feedback, feel free to continue to comment/contribute on the github project. I've also started a suggestions forum here Commented Oct 19, 2022 at 15:42
  • That's even better. One minor thing that you still can fix is that it would be better if it could scroll to the top of the output rather than to the bottom. Commented Oct 20, 2022 at 9:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .