Skip to content

Use dict.setdefault() in functools caching? #150708

@seberg

Description

@seberg

Feature or enhancement

Proposal:

Currently, functools.cache family of functions uses _PyDict_SetItem_KnownHash. But I am wondering if it shouldn't use SetDefault style access at basically no-cost?

That way, when working with many threads, while multiple evaluations are still possible, all threads are guaranteed to end up with the same object.
There may be great reasons why that isn't wanted, but on first sight it seems like a simple and practically free way to remove a pit-fall for threaded code.
(Of course building a custom version that does this is easy, but functools.cache is great and used quite a lot.)

Admittedly, an optional once= would also be a very cool feature (or maybe as a dedicated pattern).

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-featureA feature request or enhancement
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions