Message370697
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:
... |
|
Date |
User |
Action |
Args |
2020-06-04 07:34:48 | njs | set | recipients:
+ njs, rhettinger, pitrou, Antony.Lee |
2020-06-04 07:34:48 | njs | set | messageid: <1591256088.01.0.761303685596.issue31254@roundup.psfhosted.org> |
2020-06-04 07:34:47 | njs | link | issue31254 messages |
2020-06-04 07:34:47 | njs | create | |
|