This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author njs
Recipients Antony.Lee, njs, pitrou, rhettinger
Date 2020-06-04.07:34:47
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1591256088.01.0.761303685596.issue31254@roundup.psfhosted.org>
In-reply-to
Content
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:
    ...
History
Date User Action Args
2020-06-04 07:34:48njssetrecipients: + njs, rhettinger, pitrou, Antony.Lee
2020-06-04 07:34:48njssetmessageid: <1591256088.01.0.761303685596.issue31254@roundup.psfhosted.org>
2020-06-04 07:34:47njslinkissue31254 messages
2020-06-04 07:34:47njscreate