Skip to content

Commit

Permalink
Update faq on custom namespaces with new info since pyodide#1167 merged
Browse files Browse the repository at this point in the history
  • Loading branch information
Hood committed Feb 15, 2021
1 parent ad611d6 commit db0615f
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 16 deletions.
23 changes: 7 additions & 16 deletions docs/usage/faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,24 +64,15 @@ monkey patch `pyodide-py.find_imports` which takes `code` as an argument
and returns a list of packages imported.

## How can I execute code in a custom namespace?
The second argument to `eval_code` is a namespace to execute the code in.
The namespace is a python dictionary. So you can use:
The second argument to {any}`pyodide.eval_code` is a global namespace to execute the code in.
The namespace is a python dictionary.
```javascript
pyodide.runPython(`
my_namespace = { "x" : 2, "y" : 7 }
def eval_in_my_namespace(code):
return eval_code(code, my_namespace)
`);
pyodide.globals.eval_in_my_namespace("x")
let my_namespace = pyodide.globals.dict();
pyodide.pyodide_py.eval_code(`x = 1 + 1`, my_namespace);
pyodide.pyodide_py.eval_code(`y = x ** x`, my_namespace);
my_namespace.y; // ==> 4
```
which will return `2`.
<!-- TODO: change this when this is fixed! -->
Current deficiencies in the type conversions prevent the following code from working:
```
pyodide.pyodide_py.eval_code("x", pyodide.globals.ns)
```
raises `TypeError: globals must be a real dict`.

This effectively runs the code in "module scope". Like the [Python `eval` function](https://docs.python.org/3/library/functions.html?highlight=eval#eval) you can provide a third argument to `eval_code` to specify a separate `locals` dict to run code in "function scope".

## How to detect that code is run with Pyodide?

Expand Down
1 change: 1 addition & 0 deletions src/pyodide.js
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ globalThis.languagePluginLoader = (async () => {
'registerJsModule',
'unregisterJsModule',
'setInterruptBuffer',
'pyodide_py'
];

function makePublicAPI(module, public_api) {
Expand Down

0 comments on commit db0615f

Please sign in to comment.