Pyo3: Example of the generator with yield #question

Created on 2 Nov 2018  路  4Comments  路  Source: PyO3/pyo3

Hello,

Is it possible to call some python function which uses generator (would like to create it in rust part).
What is correct way to do yield(val) from pyo3 side?

Im afraid that calling from python could affect performance significantly.
Do you have any examples (with PyIterator?)?

Thank you,

question

Most helpful comment

I'm not really sure what you're trying to do exactly, but I suppose you could try the following

https://github.com/PyO3/pyo3/blob/52dfc0013c81e1372e831fa5087656dff4e26dcf/tests/test_dunder.rs#L52-L67

This will allow returning your struct to python where it can be used just like a generator.

All 4 comments

I don't think calling yield in rust is what you want; yield is just a syntactic sugar that will build an object with __iter__ and __next__ methods from that function. What you can do in rust is to create an object that has __iter__ and __next__ which you can pass to your python code.

Unfortunately, stuck a bit:

I found one example, but it uses yield:

https://pyo3.rs/master/doc/src/pyo3/types/iterator.rs.html#157

I'm not really sure what you're trying to do exactly, but I suppose you could try the following

https://github.com/PyO3/pyo3/blob/52dfc0013c81e1372e831fa5087656dff4e26dcf/tests/test_dunder.rs#L52-L67

This will allow returning your struct to python where it can be used just like a generator.

Works perfect. Thank you.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

konstin picture konstin  路  5Comments

sebpuetz picture sebpuetz  路  5Comments

davidhewitt picture davidhewitt  路  5Comments

nbigaouette picture nbigaouette  路  4Comments

davidhewitt picture davidhewitt  路  6Comments