Python: store extra data for objects in a WeakKeyDictionary 0 ▲ Adam Johnson 1 day ago · Tech · hide · 0 comments In several programs, I’ve wanted to solve the problem of associating extra data with an object. For example, in django-upgrade, the individual “fixer” functions often want to store extra data per visited ast.Module object. A common pattern in Python is to store the data in an extra attribute directly on the object, like module._all_used_names = .... However, this approach has some downsides: The object may not allow arbitrary attributes, such as for built-in types like dict or slotted classes. Attribute names can collide across use cases. Defences against this include using a long, verbose attribute name and prefixing it with an underscore, but they don’t provide any guarantees. Attributes may confusingly appear in other code paths that expose all attributes on the object, such as where vars() is used. Here’s a pattern that I’ve used to (mostly) avoid these issues: import ast from weakref import WeakKeyDictionary used_names_cache: WeakKeyDictionary[ast.Module, set[str]] =… No comments yet. Log in to reply on the Fediverse. Comments will appear here.