dabeaz / curio

Good Curio!
Other
4.01k stars 240 forks source link

ContextTask do not copy parents context #356

Open vytasrgl opened 1 year ago

vytasrgl commented 1 year ago

Using ContextTask class currently creates empty context for each of the tasks. The desirable behavior would be that child tasks would have access to the parent task context.

Right now it seems its hard to implement the way that would solve it only by modifying the ContextTask code, however it can be solved by running task creation in the parent's context:

        # Create a new task. Putting it on the ready queue
        def new_task(coro):
            # Children should be created with parent context if any
            nonlocal current
            if current and current._context:
                task = current._context.run(taskcls, coro)
            else:
                task = taskcls(coro)
            tasks[task.id] = task
            reschedule_task(task)
            for a in _activations:
                a.created(task)
            return task
dabeaz commented 1 year ago

Just to make sure that I understand this, the primary issue is that new tasks aren't created within the context of the parent task?

All things equal, I don't want the Curio core to be dependent on contextvars. However, it may be possible to restructure things slightly to make this possible. I will investigate.

vytasrgl commented 1 year ago

Yes, indeed, the issue that the new tasks are created outside current context, so those tasks cant access the parent context.

I endup using this patch which does not incluide too much dependancies in the core, but still there are probably better ways to do this. https://github.com/hansonrobotics/curio/commit/1c56eaf7b3b6141ba59be26ab65888782e93f029

dabeaz commented 1 year ago

I made a modification to have the parent task passed to the Task.__init__() method. Let me know if this addresses the problem.