Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

gh-125400: add async generator return value#125401

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Draft
alex-dixon wants to merge3 commits intopython:main
base:main
Choose a base branch
Loading
fromalex-dixon:async-generator-return

Conversation

alex-dixon
Copy link

@alex-dixonalex-dixon commentedOct 13, 2024
edited by bedevere-appbot
Loading

benedikt-bartscher reacted with thumbs up emoji
@ghost
Copy link

ghost commentedOct 13, 2024
edited by ghost
Loading

All commit authors signed the Contributor License Agreement.
CLA signed

@bedevere-app
Copy link

Most changes to Pythonrequire a NEWS entry. Add one using theblurb_it web app or theblurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply theskip news label instead.

@AlexWaygood
Copy link
Member

Thanks for writing a reference implementation for this idea as was requested in the Discourse thread; it makes it much easier to evaluate the proposal! I'm marking the PR asDO-NOT-MERGE for now, however, since a change this significant would almost certainly require a PEP in order for it to be accepted (but I think you're aware of this already!).

Eclips4, JelleZijlstra, ZeroIntensity, mikegai, and alex-dixon reacted with thumbs up emoji

@bedevere-app
Copy link

Most changes to Pythonrequire a NEWS entry. Add one using theblurb_it web app or theblurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply theskip news label instead.

Copy link
Member

@ZeroIntensityZeroIntensity left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Some initial comments. I do realize that a lot of this is copied from theStopIteration implementation, so it might be better to ignore some of my comments for consistency (or better yet, apply my comments toStopIteration as well 😄)

Overall, I think this is nice for consistency withStopIteration, but I don't think this is particularly useful without support foryield from in async generators, because you can implement this just fine in current versions--just define an exception with avalue attribute, and raise it.

JelleZijlstra reacted with thumbs up emoji
return -1;
}
if (value == NULL) {
value = Py_NewRef(Py_None);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Py_None is immortal, I don't think we need to incref it. There's some contention about this, though.

Suggested change
value=Py_NewRef(Py_None);
value=Py_None;

Comment on lines +226 to +233
PyObject *value = NULL;
if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) {
PyObject *exc = PyErr_GetRaisedException();
value = Py_NewRef(((PyStopAsyncIterationObject *)exc)->value);
Py_DECREF(exc);
} else if (PyErr_Occurred()) {
return -1;
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

There's going to be a lot of internal reusing of_PyThreadState_GET with this approach. You can use the private API:

Suggested change
PyObject*value=NULL;
if (PyErr_ExceptionMatches(PyExc_StopAsyncIteration)) {
PyObject*exc=PyErr_GetRaisedException();
value=Py_NewRef(((PyStopAsyncIterationObject*)exc)->value);
Py_DECREF(exc);
}elseif (PyErr_Occurred()) {
return-1;
}
PyObject*value=NULL;
PyThreadState*tstate=_PyThreadState_GET();
PyObject*occurred=_PyErr_Occurred(tstate);
if (PyErr_GivenExceptionMatches(occurred,PyExc_StopAsyncIteration)) {
PyObject*exc=_PyErr_GetRaisedException(tstate);
value=Py_NewRef(((PyStopAsyncIterationObject*)exc)->value);
Py_DECREF(exc);
}elseif (occurred) {
return-1;
}

Comment on lines +189 to +210
if (value == NULL ||
(!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))
{
/* Delay exception instantiation if we can */
PyErr_SetObject(PyExc_StopAsyncIteration, value);
return 0;
}
/* Construct an exception instance manually with
* PyObject_CallOneArg and pass it to PyErr_SetObject.
*
* We do this to handle a situation when "value" is a tuple, in which
* case PyErr_SetObject would set the value of StopIteration to
* the first element of the tuple.
*
* (See PyErr_SetObject/_PyErr_CreateException code for details.)
*/
e = PyObject_CallOneArg(PyExc_StopAsyncIteration, value);
if (e == NULL) {
return -1;
}
PyErr_SetObject(PyExc_StopAsyncIteration, e);
Py_DECREF(e);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Same story here--use the thread state.

Suggested change
if (value==NULL||
(!PyTuple_Check(value)&& !PyExceptionInstance_Check(value)))
{
/* Delay exception instantiation if we can */
PyErr_SetObject(PyExc_StopAsyncIteration,value);
return0;
}
/*Constructanexceptioninstancemanuallywith
*PyObject_CallOneArgandpassittoPyErr_SetObject.
*
*Wedothistohandleasituationwhen"value"isatuple,inwhich
*casePyErr_SetObjectwouldsetthevalueofStopIterationto
*thefirstelementofthetuple.
*
* (SeePyErr_SetObject/_PyErr_CreateExceptioncodefordetails.)
*/
e=PyObject_CallOneArg(PyExc_StopAsyncIteration,value);
if (e==NULL) {
return-1;
}
PyErr_SetObject(PyExc_StopAsyncIteration,e);
Py_DECREF(e);
PyThreadState*tstate=_PyThreadState_GET();
if (value==NULL||
(!PyTuple_Check(value)&& !PyExceptionInstance_Check(value)))
{
/* Delay exception instantiation if we can */
_PyErr_SetObject(tstate,PyExc_StopAsyncIteration,value);
return0;
}
/*Constructanexceptioninstancemanuallywith
*PyObject_CallOneArgandpassittoPyErr_SetObject.
*
*Wedothistohandleasituationwhen"value"isatuple,inwhich
*casePyErr_SetObjectwouldsetthevalueofStopIterationto
*thefirstelementofthetuple.
*
* (SeePyErr_SetObject/_PyErr_CreateExceptioncodefordetails.)
*/
e=PyObject_CallOneArg(PyExc_StopAsyncIteration,value);
if (e==NULL) {
return-1;
}
_PyErr_SetObject(tstate,PyExc_StopAsyncIteration,e);
Py_DECREF(e);

Py_ssize_t size = PyTuple_GET_SIZE(args);
PyObject *value;

if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Typically, the convention is to use< 0 rather than== -1

Suggested change
if (BaseException_init((PyBaseExceptionObject*)self,args,kwds)==-1)
if (BaseException_init((PyBaseExceptionObject*)self,args,kwds)<0)

Comment on lines +618 to +622
if (size > 0)
value = PyTuple_GET_ITEM(args, 0);
else
value = Py_None;
self->value = Py_NewRef(value);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

This can get simplified a little, asNone is immortal like I mentioned:

Suggested change
if (size>0)
value=PyTuple_GET_ITEM(args,0);
else
value=Py_None;
self->value=Py_NewRef(value);
if (size>0) {
self->value=Py_NewRef(PyTuple_GET_ITEM(args,0));
}
else {
self->value=Py_None;
}


if (BaseException_init((PyBaseExceptionObject *)self, args, kwds) == -1)
return -1;
Py_CLEAR(self->value);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

WhyCLEAR it here? It's an extra operation of setting it toNULL when nothing will touch it in between calls here anyway.

Suggested change
Py_CLEAR(self->value);
Py_DECREF(self->value);

Comment on lines +352 to +357
if (result == Py_None) {
PyErr_SetNone(PyExc_StopAsyncIteration);
}
else {
_PyGen_SetStopAsyncIterationValue(result);
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Consider acquiring the thread state here, and then passing that to_PyGen_SetStopAsyncIterationValue (to omit an extra call there)

Comment on lines 2067 to 2070
async def gen():
yield 1
yield 2
return 3

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

It might be a good idea to add a dummy coroutine (something likeasyncio.sleep(0) should work) here, as that needs to get yielded in a different way--in my experience with dealing with the coroutine implementation, a coroutine that awaits nothing behaves differently than one that does.

alex-dixon reacted with thumbs up emoji
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Thanks so much for your thorough and prompt review. I've updated this to include awaited calls toasyncio.sleep.

@bedevere-app
Copy link

Most changes to Pythonrequire a NEWS entry. Add one using theblurb_it web app or theblurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply theskip news label instead.

@pkch
Copy link

pkch commentedFeb 1, 2025
edited
Loading

Some initial comments. I do realize that a lot of this is copied from theStopIteration implementation, so it might be better to ignore some of my comments for consistency (or better yet, apply my comments toStopIteration as well 😄)

Overall, I think this is nice for consistency withStopIteration, but I don't think this is particularly useful without support foryield from in async generators, because you can implement this just fine in current versions--just define an exception with avalue attribute, and raise it.

I believe the strongest argument in favor of this feature even without ayield from is in this post:https://discuss.python.org/t/allow-return-statements-with-values-in-asynchronous-generators/66886/27 IMHO, (1) being able to easily switch between sync/async is of great value, and (2) theell library referenced there is very useful. I understand this use case might look quite niche, but generally refactoring between sync and async code isn't that rare (and would be even less rare if it wasn't so hard).

Separately from the above, IIUC,@MadcowD might have been interested in writing a reference implementation foryield from? Though I may have misread the posts on that topic, so please correct me if I'm wrong.

@JelleZijlstraJelleZijlstra removed their request for reviewMay 4, 2025 16:16
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers

@ZeroIntensityZeroIntensityZeroIntensity requested changes

@willingcwillingcAwaiting requested review from willingcwillingc is a code owner

@AlexWaygoodAlexWaygoodAwaiting requested review from AlexWaygoodAlexWaygood is a code owner

@iritkatrieliritkatrielAwaiting requested review from iritkatrieliritkatriel is a code owner

@markshannonmarkshannonAwaiting requested review from markshannonmarkshannon is a code owner

@AA-TurnerAA-TurnerAwaiting requested review from AA-TurnerAA-Turner will be requested when the pull request is marked ready for reviewAA-Turner is a code owner

@JelleZijlstraJelleZijlstraAwaiting requested review from JelleZijlstraJelleZijlstra will be requested when the pull request is marked ready for reviewJelleZijlstra is a code owner

Assignees
No one assigned
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

4 participants
@alex-dixon@AlexWaygood@pkch@ZeroIntensity

[8]ページ先頭

©2009-2025 Movatter.jp