Debian Codegraph @

pypy/module/cpyext/contextvars.py

raw symbols SCIP
1 # Implement the PyContextVar* functions in terms of the pure-python
2 # _contextvars module
3
4 from pypy.module.cpyext.api import (cpython_api, PyObject, PyObjectP,
5 CONST_STRING)
6 from pypy.module.cpyext.pyobject import make_ref, from_ref
7 from rpython.rtyper.lltypesystem import rffi
8 from pypy.module.cpyext.pyobject import incref
9 from pypy.interpreter.error import OperationError
10
11 @cpython_api([CONST_STRING, PyObject], PyObject)
12 def PyContextVar_New(space, name, default):
13 if name:
14 w_str = space.newbytes(rffi.charp2str(name))
15 w_name = space.call_method(w_str, 'decode', space.newtext("utf-8"))
16 else:
17 w_name = space.newtext('')
18 if default:
19 w_def = from_ref(space, default)
20 return space.appexec([w_name, w_def], """(name, default):
21 from _contextvars import ContextVar
22 return ContextVar(name, default=default)
23 """)
24 else:
25 return space.appexec([w_name], """(name,):
26 from _contextvars import ContextVar
27 return ContextVar(name)
28 """)
29
30 @cpython_api([PyObject, PyObject], PyObject)
31 def PyContextVar_Set(space, w_ovar, w_val):
32 return space.appexec([w_ovar, w_val], """(ovar, val):
33 from _contextvars import ContextVar
34 if not isinstance(ovar, ContextVar):
35 raise TypeError('an instance of ContextVar was expected')
36 return ovar.set(val)
37 """)
38
39 @cpython_api([PyObject, PyObject], rffi.INT_real, error=-1)
40 def PyContextVar_Reset(space, w_ovar, w_token):
41 space.appexec([w_ovar, w_token], """(ovar, token):
42 from _contextvars import ContextVar
43 if not isinstance(ovar, ContextVar):
44 raise TypeError('an instance of ContextVar was expected')
45 return ovar.reset(token)
46 """)
47 return 0
48
49 @cpython_api([PyObject, PyObject, PyObjectP], rffi.INT_real, error=-1)
50 def PyContextVar_Get(space, w_ovar, default, val):
51 if default:
52 w_def = from_ref(space, default)
53 w_ret = space.appexec([w_ovar, w_def], """(ovar, default):
54 from _contextvars import ContextVar
55 if not isinstance(ovar, ContextVar):
56 raise TypeError('an instance of ContextVar was expected')
57 return ovar.get(default)
58 """)
59 else:
60 try:
61 w_ret = space.appexec([w_ovar], """(ovar,):
62 from _contextvars import ContextVar
63 if not isinstance(ovar, ContextVar):
64 raise TypeError('an instance of ContextVar was expected')
65 return ovar.get()
66 """)
67 except OperationError as e:
68 if e.match(space, space.w_LookupError):
69 val[0] = rffi.cast(PyObject, 0)
70 return 0
71 raise e
72 val[0] = make_ref(space, w_ret)
73 return 0