Banias Baabe’s Post

Stop passing the same variable through five different functions in Python. We have all been there. You need a user ID in a deeply nested database call. So you clutter up every single function signature just to pass it down. Thread local storage used to be the classic workaround for this problem. But modern asynchronous programming breaks thread locals entirely. If async task A pauses and task B takes over, they share the same underlying thread. That means they suddenly share the same thread local variables. This is a fast track to silent data corruption in concurrent applications. Try the Python 𝗰𝗼𝗻𝘁𝗲𝘅𝘁𝘃𝗮𝗿𝘀 module. It solves this by storing state that is strictly bound to your current asynchronous task. You simply declare a 𝗖𝗼𝗻𝘁𝗲𝘅𝘁𝗩𝗮𝗿 object at the top of your module. When a new web request arrives, you use the set method to store the request data. Any function running inside that specific task can then use the get method to retrieve it. Even if a hundred other concurrent tasks are running, they will only see their own isolated values. You get the convenience of global access without the nightmare of shared global state. Your function signatures stay clean and focused on their actual business logic. --- ♻️ Found this useful? Share it with another builder. ➕ For daily practical AI and Python posts, follow Banias Baabe.

  • text

Isn't this exact same content faced a backlash last time it was shared, because it is just a glorified "global"

I wouldn’t use this too often personally. The example shown, logging, is a good one. But I wouldn’t want to use it heavily for something like user_id required for a database call — IMO for a situation like that it hinders both code reuse potential and readability. Plus it makes unit testing quite a bit weirder than it should be.

See more comments

To view or add a comment, sign in

Explore content categories