Nathaniel Smith <n...@pobox.com> added the comment:

Just found this while searching to see if we had an existing way to combine 
WeakValueDictionary + defaultdict. The use case I've run into a few times is 
where you need a keyed collection of mutexes, like e.g. asyncio.Lock objects. 
You want to make sure that if there are multiple tasks trying to access the 
same key/resource, they all acquire the same lock, but you don't want to use a 
regular defaultdict, because that will end up growing endlessly as different 
keys/resources are encountered.

It'd be very handy to do something like:

lock_dict = WeakValueDictionary(default=asyncio.Lock)

async with lock_dict[key]:
    ...

and have everything magically work.

The alternative is to open-code the default handling at the call site, either:

# Wasteful: creates a new Lock object on every usage,
# regardless of whether it's actually needed.
async with lock_dict.setdefault(key, asyncio.Lock()):
    ...

Or else the verbose:

lock = lock_dict.get(key)
if lock is None:
    lock = lock_dict[key] = asyncio.Lock()
async with lock:
    ...

----------
nosy: +njs

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue31254>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to