Skip to content

Expanded Cross Language Iterator Support #309

@wiwichips

Description

@wiwichips

Describe your feature request here.

Feature Request

I would love if you could use Python's next(...) to iterate over an iterator defined in JavaScript in Python. Similarly, I'd love if you could call .next() on an iterator defined in Python passed to a JavaScript function.

Or at least if there was a way to iterate over Python iterators in JavaScript since I don't think that's possible right now (unless you add a python function to do it).

Note: This feature request kind of implies there would need to be support for Iterable objects, async iterators and other types of generators - I just focused it on simple iterators back and forth as the primary example.

Current behaviour (as of PythonMonkey 0.4.0):

Iterating over a JavaScript iterator in Python

>>> myit = pm.eval('function* makeIt() { yield 1; yield 2; }; makeIt')()
>>> myit.next()
{'value': 1.0, 'done': False}
>>> myit.next()
{'value': 2.0, 'done': False}
>>> next(myit)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict' object is not an iterator

Iterating over a Python iterator in JavaScript

>>> myit = iter((1, 2))
>>> pm.eval('(myit) => { console.log(myit.next()); console.log(myit.next()); }')(myit)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
pythonmonkey.SpiderMonkeyError: Error in file evaluate, on line 1, column 30:
TypeError: myit.next is not a function
Stack Trace:
  @evaluate:1:30

How is this handled in Pyodide?

Iterating over a JavaScript iterator in Python
There is a JsIterator which allows JavaScript iterators to be iterated in Python using next(obj)

Iterating over a Python iterator in JavaScript
There is a PyIterator Pyodide PyProxy which allows Python iterators passed to JavaScript to have a obj.next() which I think calls the Python code next(obj). This enables it to work as expected such as in for(let x of proxy){} in JS.

Misc notes

Code example

No response

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

Status

Done

Relationships

None yet

Development

No branches or pull requests

Issue actions