← Back to context

Comment by boothby

7 days ago

Just a heads up, this fails to track usage of get and setdefault. The ability to iterate over dicts makes the whole question rather murky.

I didn't know about the setdefault method, and wouldn't have guessed it lets you read a value. Interesting, thanks.

Another way to get data out would be to use the new | operator (i.e. x = {} | y essentially copies dictionary x to y) or the update method or ** unpacking operator (e.g. x = {**y}). But maybe those come under the umbrella of iterating as you mentioned.

  • setdefault was a go to method before defaultdict was added to the collections module in Python 2.5, which replaced the biggest use case.

    • It's been some time since I last benchmarked defaultdict but last time I did (circa 3.6 and less?), it was considerably slower than judicious use of setdefault.

      3 replies →

Indeed. Inheriting from 'collections.UserDict' instead of 'dict' will make TFA's code work as intended for most of those edge cases.

UserDict will route '.get', '.setdefault', and even iteration via '.items()' through the '__getitem__' method.

edited to remove "(maybe all?) edge cases". As soon as I posted, I thought of several less common/obvious edge cases.

Along with those and iteration, it also would need to handle del/pop/popitem/update/copy/or/ror/... some of which might necessitate a decision on whether comparisons/repr also count as access.