Skip to content

Commit

Permalink
feat: use contextvars.ConvextVar instead of threading.local in Python 3
Browse files Browse the repository at this point in the history
Closes #504 

Co-authored-by: ndavydovdev <ndavydov@aita.travel>
  • Loading branch information
Chris Rossi and ndavydovdev authored Aug 12, 2020
1 parent 6c18b95 commit 4c634f3
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
41 changes: 36 additions & 5 deletions google/cloud/ndb/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,43 @@
from google.cloud.ndb import tasklets


class _LocalState(threading.local):
"""Thread local state."""
try: # pragma: NO PY2 COVER
import contextvars

def __init__(self):
self.context = None
self.toplevel_context = None
class _LocalState:
"""Thread local state."""

def __init__(self):
self._toplevel_context = contextvars.ContextVar(
"_toplevel_context", default=None
)
self._context = contextvars.ContextVar("_context", default=None)

@property
def context(self):
return self._context.get()

@context.setter
def context(self, value):
self._context.set(value)

@property
def toplevel_context(self):
return self._toplevel_context.get()

@toplevel_context.setter
def toplevel_context(self, value):
self._toplevel_context.set(value)


except ImportError: # pragma: NO PY3 COVER

class _LocalState(threading.local):
"""Thread local state."""

def __init__(self):
self.context = None
self.toplevel_context = None


_state = _LocalState()
Expand Down
4 changes: 4 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import io
import os
import sys

import setuptools

Expand All @@ -28,6 +29,9 @@ def main():
"redis",
]

if sys.version_info.major == 3 and sys.version_info.minor < 7:
dependencies.append("contextvars")

setuptools.setup(
name="google-cloud-ndb",
version = "1.4.2",
Expand Down

0 comments on commit 4c634f3

Please sign in to comment.