jupyterlite / pyodide-kernel

Python kernel for JupyterLite powered by Pyodide
https://jupyterlite-pyodide-kernel.readthedocs.io/en/latest/_static/
BSD 3-Clause "New" or "Revised" License
46 stars 23 forks source link

Value of global variable could not been gotten through pyodide.globals.get() #137

Open MRYingLEE opened 1 month ago

MRYingLEE commented 1 month ago

In a Jupyterlite with slightly customized Pyodide environment, I failed to access value of a global variable. In UI, I ran the following assignment statement in a cell:

a=1

In some customized code, I ran the following Typescript code for testing:

          const { globals } = this._pyodide;
          const a_before = globals.get("a");
          if (a_before)
            try {
              console.log(`Before run, the value is ${a_before}.`);
            } catch (err: any) {
              console.error(err);
              console.log(`Before run, the value is ${a_before.toJS()}.`);
            }

          await this._pyodide.loadPackagesFromImports(newCode);
          const result = await this._pyodide.runPythonAsync(newCode);

          if (result)
            console.log(`After run, the result is ${result}`);

          const a_after = globals.get("a");
          if (a_after)
            try {
              console.log(`After run, the value is ${a_after}.`);
            } catch (err: any) {
              console.error(err);
              console.log(`After run, the value is ${a_after.toJS()}.`);
            }

It failed to get the value of the global variable. But if the newCode assigned some value to vaiable "a", then the globals.get("a") would succeed afterwards.

It seems the namespace of Pyodide kernel is independent to that of pyodide.runPythonAsync().

Please clarify. Thanks,

jtpio commented 3 weeks ago

In some customized code, I ran the following Typescript code for testing:

Curious where you run this code?

MRYingLEE commented 3 weeks ago

I put my testing code in the function of async execute(content: any, parent: any) , with an if-else branch near https://github.com/jupyterlite/pyodide-kernel/blob/67a976f0d8c8d21e246f46703c3940bb5f95e187/packages/pyodide-kernel/src/worker.ts#L307.

In future, the code will be run in a Jupyterlab frontend extension. For example, to let AI explain code along with the current values of the used global variables.