PyCall.jl icon indicating copy to clipboard operation
PyCall.jl copied to clipboard

Howto - Python yield statement

Open RickDW opened this issue 1 year ago • 1 comments

Hi folks, not sure if this is the best place to get some advice, feel free to let me know if it's not. I'm trying to implement a Python class which has one method that uses two yield statements. My current PyCall implementation is this, but it gives me a "SyntaxError: 'yield' outside function":

using PyCall

textual = pyimport("textual")
pyimport("textual.app")
pyimport("textual.widgets")


@pydef mutable struct StopwatchApp <: textual.app.App
    function compose(self)
        py"""
        yield textual.widgets.Header()
        yield textual.widgets.Footer()
        """
    end
end

The full error is this:

Traceback (most recent call last)
in <lambda>:1

/home/name/.julia/packages/PyCall/1gn3u/src/pyeval.jl:1
const Py_single_input = 256 # from Python.h

SyntaxError: 'yield' outside function

yield doesn't seem to be discussed in PyCall's docs so I'm wondering if there's an implementation for this. Please give me a shout if you can help me out :)

RickDW avatar Mar 29 '24 23:03 RickDW

The Python yield statement is only valid inside a Python function — that is, your py"..." block needs to include a whole function def foo(...): ... and not just a function body.

stevengj avatar Mar 30 '24 17:03 stevengj