Request.get_current. How is it reset?


I’m digging in the Request.get_current() method that returns the current Request instance, using ContextVars.

So far, so good. But from my own understanding, when the request has ended, it should remove itself from the ContextVar, by calling cls._current.reset(token).

Except, it’s not the case at Sanic. I haven’t found where the reset() is called.

Why is that? Is it done automatically when the request is - somehow - deleted upon completion ?

Thank you for that clarification!

We do not call reset.

Python has native support for context vars in asyncio, and we are relying upon that. Each connection is its own task, and when a Request starts, we set the value.

Not calling reset does not appear to be an issue, but I am happy to be corrected if I am wrong.

That’s … surprising! I didn’t knew it wouldn’t increase the stack like this!!

Thank you for that clarification.

I do have one last thing to ask: How do you come up with this way of thinking? Reading the doc pushes you to use get/set AND reset. How/Why made you say “nope, no need for reset” ?!

(I’m asking because I believe I can broaden my expertise with your advice :wink: )

Testing… :laughing: I write a lot of small little snippets and use things like timy (for performance) and tracemalloc (for memory) to what might be an optimal way to write some snippet. I’ve seen no indication there is a memory leak, so I would just as much prefer to avoid an extra call.

Thank you, I’ll look into timy and tracemalloc!

If there are no memory leak, it makes sense to not add an extra call.

Thanks for the tips!