On Fri, May 28, 2021 at 5:25 AM Shreyan Avigyan email@example.com wrote:
This is thread-safe:
from threading import Lock
lock = Lock() counter = 0 def get_next(): with lock: global counter counter += 1 my_counter = counter
This is a great workaround. I can try to improve this. But first of all should we depend on the user to do this locking? I don't think so. So is it possible to implement this in the background without affecting current performance?
No, you can't, because it's impossible to know when you're done mutating. However, if the mutation is inherently atomic - or if subsequent lookups don't require atomicity - then the lock becomes unnecessary, and your code will be thread-safe already.
(If you use async functions or recursion but no threads, then every yield point becomes explicit in the code, and you effectively have a lock that governs every block of code between those points. But that has many many other implications. Point is, statics should be compatible with ALL use-cases, and that shouldn't be difficult.)