Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to contextvars in asyncio add_done_callback callback

In Python async function I'am creating ContextVar, task and attaching callback to it:

bbb = contextvars.ContextVar('aaa')
bbb.set(3)
task = self.loop.create_task(self.someFunc())
task.add_done_callback(self.commonCallback)
bbb.set(4)

In callback I first start debugger:

def commonCallback(self, result):
 pdb.set_trace()
 try:
  r = result.result()
  print(r)
 except:
  self.log.exception('commonCallback')

And in debugger:

-> try:
(Pdb) bbb.get()
*** NameError: name 'bbb' is not defined
(Pdb) ctx = contextvars.copy_context()
(Pdb) print(list(ctx.items()))
[(<ContextVar name='aaa' at 0xa8245df0>, 3)]
(Pdb) 

ContextVar is there, but I can't access it. So, I am missing something, but can't find what?

like image 778
ljweko Avatar asked Jan 30 '26 20:01

ljweko


1 Answers

The bbb local variable is defined in one place, so it won't be automatically accessible in another, such as the commonCallback function defined elsewhere in the code. The documentation states that "Context Variables should be created at the top module level", so you should try that first.

like image 120
user4815162342 Avatar answered Feb 02 '26 10:02

user4815162342