flatironinstitute / stan-playground

Run Stan models in the browser
Apache License 2.0
36 stars 1 forks source link

Improve errors from pyodide by using filename #244

Closed WardBrian closed 3 weeks ago

WardBrian commented 3 weeks ago

This also uses the async call function, as this lets users call micropip

WardBrian commented 3 weeks ago

Two changes:

  1. Tracebacks now mention the name of the file, rather than the <exec> string: Before:

    File "<exec>", line 2
    ,
    ^
    SyntaxError: invalid syntax

    Now:

    File "data.py", line 2
    ,
    ^
    SyntaxError: invalid syntax
  2. You can use top-level awaits, which lets you use micropip

    import micropip
    await micropip.install("scikit-learn")
jsoules commented 3 weeks ago

Tried the following code in data.py:

import asyncio

async def foo():
  print("Hello")
  await asyncio.sleep(1)
  print("...world!")

await foo()

Before the change:

PythonError: sys:1: RuntimeWarning: coroutine 'foo' was never awaited
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Traceback (most recent call last):
  File "/lib/python312.zip/_pyodide/_base.py", line 501, in eval_code
    .compile()
     ^^^^^^^^^
  File "/lib/python312.zip/_pyodide/_base.py", line 280, in compile
    self._gen.send(self.ast)
  File "/lib/python312.zip/_pyodide/_base.py", line 163, in _parse_and_compile_gen
    return compile(mod, filename, mode, flags=flags)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<exec>", line 10
SyntaxError: 'await' outside function

Note error is listed as originating in File "<exec>".

After the change:

Hello

...world!

PythonError: Traceback (most recent call last):
  File "/lib/python312.zip/_pyodide/_base.py", line 574, in eval_code_async
    await CodeRunner(
  File "/lib/python312.zip/_pyodide/_base.py", line 396, in run_async
    await coroutine
  File "data.py", line 14, in <module>
    raise ValueError("data is not defined")
ValueError: data is not defined

Still an error, but only because I didn't actually generate any data for data.json. Source of the error is File: "data.py".

I think this is a good change and checks out--let's ship it.