Skip to content
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#9719] Support contextvars in coroutines #1192

Merged
merged 27 commits into from
May 1, 2020
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
2006d09
failing test
hawkowl Oct 19, 2019
3c020d0
fix impl and add more tests
hawkowl Oct 19, 2019
6c16077
changelog
hawkowl Oct 20, 2019
e003a0a
fixes
hawkowl Oct 20, 2019
03d4605
fixes
hawkowl Oct 20, 2019
76fad8a
fixes
hawkowl Oct 20, 2019
29f835c
fixes
hawkowl Oct 20, 2019
fd8be59
Merge branch 'trunk' into 9719-contextvars
hawkowl Oct 20, 2019
f1e7838
fixes
hawkowl Oct 20, 2019
67d1297
test for async await
hawkowl Oct 25, 2019
7693044
Merge remote-tracking branch 'origin/trunk' into 9719-contextvars
hawkowl Oct 25, 2019
03180a4
linting errors
hawkowl Oct 27, 2019
2dec49c
lint
hawkowl Oct 28, 2019
6fb9987
Merge branch 'trunk' into 9719-contextvars
hawkowl Nov 11, 2019
0ab920b
dont use a broken pywin32
hawkowl Nov 11, 2019
9123b41
Merge branch '9719-contextvars' of github.com:twisted/twisted into 97…
hawkowl Nov 11, 2019
cc73065
Merge branch 'trunk' into 9719-contextvars
glyph Nov 12, 2019
b7a1efe
Merge branch 'trunk' into 9719-contextvars
hawkowl Nov 12, 2019
bb2544c
Merge branch 'trunk' into 9719-contextvars
glyph Feb 25, 2020
b6952f1
Merge remote-tracking branch 'origin/trunk' into 9719-contextvars
hawkowl Apr 26, 2020
b3f6976
fix lint
hawkowl Apr 26, 2020
56469b1
set to just async/await and inlinecallbacks
hawkowl Apr 30, 2020
369d361
fix 3.5/3.6 giving different warnings
hawkowl Apr 30, 2020
cd96d14
fix
hawkowl Apr 30, 2020
065e3bf
newsfile update
hawkowl Apr 30, 2020
dc56137
address trivial lint failures
glyph May 1, 2020
10ee73c
focus on the feature in the changelog entry rather than the implement…
glyph May 1, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 61 additions & 23 deletions src/twisted/internet/defer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from __future__ import division, absolute_import, print_function

import attr
import functools
import traceback
import types
import warnings
Expand All @@ -28,11 +29,13 @@

# Twisted imports
from twisted.python.compat import cmp, comparable
from twisted.python import lockfile, failure
from twisted.python import lockfile, failure, reflect
from twisted.logger import Logger
from twisted.python.deprecate import warnAboutFunction, deprecated

log = Logger()
_contextvars = reflect.requireModule('contextvars')
hawkowl marked this conversation as resolved.
Show resolved Hide resolved



class AlreadyCalledError(Exception):
Expand Down Expand Up @@ -257,14 +260,14 @@ class Deferred:

_chainedTo = None

def __init__(self, canceller=None):
def __init__(self, canceller=None, context=None):
"""
Initialize a L{Deferred}.

@param canceller: a callable used to stop the pending operation
scheduled by this L{Deferred} when L{Deferred.cancel} is
invoked. The canceller will be passed the deferred whose
cancelation is requested (i.e., self).
scheduled by this L{Deferred} when L{Deferred.cancel} is invoked.
The canceller will be passed the deferred whose cancelation is
requested (i.e., self).

If a canceller is not given, or does not invoke its argument's
C{callback} or C{errback} method, L{Deferred.cancel} will
Expand All @@ -280,13 +283,28 @@ def __init__(self, canceller=None):

@type canceller: a 1-argument callable which takes a L{Deferred}. The
return result is ignored.

@param context: The context that this Deferred should run its callbacks
under.

@type context: L{contextvars.Context}
"""
self.callbacks = []
self._canceller = canceller
if self.debug:
self._debugInfo = DebugInfo()
self._debugInfo.creator = traceback.format_stack()[:-1]

if _contextvars and context is None:
hawkowl marked this conversation as resolved.
Show resolved Hide resolved
self._context = _contextvars.copy_context()
elif _contextvars is None and context:
raise Exception(
hawkowl marked this conversation as resolved.
Show resolved Hide resolved
"Manually supplying a contextvars context is not supported "
"if contextvars is not installed."
)
else:
self._context = context


def addCallbacks(self, callback, errback=None,
callbackArgs=None, callbackKeywords=None,
Expand Down Expand Up @@ -649,10 +667,17 @@ def _runCallbacks(self):
try:
current._runningCallbacks = True
try:
originalCallback = callback
if _contextvars:
callback = functools.partial(
hawkowl marked this conversation as resolved.
Show resolved Hide resolved
current._context.run, callback
)

current.result = callback(current.result, *args, **kw)

if current.result is current:
warnAboutFunction(
callback,
originalCallback,
"Callback returned the Deferred "
"it was attached to; this breaks the "
"callback chain and will raise an "
Expand Down Expand Up @@ -1400,17 +1425,29 @@ def _inlineCallbacks(result, g, status):
# loop and the waiting variable solve that by manually unfolding the
# recursion.

waiting = [True, # waiting for result?
None] # result
waiting = [True, # waiting for result?
None] # result

if _contextvars:
hawkowl marked this conversation as resolved.
Show resolved Hide resolved
current_context = _contextvars.copy_context()

while 1:
try:
# Send the last result back as the result of the yield expression.
isFailure = isinstance(result, failure.Failure)
if isFailure:
result = result.throwExceptionIntoGenerator(g)

if _contextvars:
if isFailure:
result = current_context.run(
hawkowl marked this conversation as resolved.
Show resolved Hide resolved
result.throwExceptionIntoGenerator, g
)
else:
result = current_context.run(g.send, result)
else:
result = g.send(result)
if isFailure:
result = result.throwExceptionIntoGenerator(g)
else:
result = g.send(result)
except StopIteration as e:
# fell off the end, or "return" statement
status.deferred.callback(getattr(e, "value", None))
Expand Down Expand Up @@ -1466,8 +1503,11 @@ def gotResult(r):
waiting[0] = False
waiting[1] = r
else:
# We are not waiting for deferred result any more
_inlineCallbacks(r, g, status)
if _contextvars:
current_context.run(_inlineCallbacks, r, g, status)
else:
# We are not waiting for deferred result any more
_inlineCallbacks(r, g, status)

result.addBoth(gotResult)
if waiting[0]:
Expand Down Expand Up @@ -2002,13 +2042,11 @@ def _tryLock():



__all__ = ["Deferred", "DeferredList", "succeed", "fail", "FAILURE", "SUCCESS",
"AlreadyCalledError", "TimeoutError", "gatherResults",
"maybeDeferred", "ensureDeferred",
"waitForDeferred", "deferredGenerator", "inlineCallbacks",
"returnValue",
"DeferredLock", "DeferredSemaphore", "DeferredQueue",
"DeferredFilesystemLock", "AlreadyTryingToLockError",
"CancelledError",
]

__all__ = [
"Deferred", "DeferredList", "succeed", "fail", "FAILURE", "SUCCESS",
"AlreadyCalledError", "TimeoutError", "gatherResults",
"maybeDeferred", "ensureDeferred",
"waitForDeferred", "deferredGenerator", "inlineCallbacks", "returnValue",
"DeferredLock", "DeferredSemaphore", "DeferredQueue",
"DeferredFilesystemLock", "AlreadyTryingToLockError", "CancelledError",
]
1 change: 1 addition & 0 deletions src/twisted/newsfragments/9719.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
twisted.internet.defer.Deferred will now capture the current contextvars context when created, and run callbacks using that context. This functionality requires Python 3.7+, or the contextvars PyPI backport to be installed for Python 3.5-3.6.
Loading