9 ms·
A Python dict that can report which keys you did not use
- jraph 1y agoI did exactly the same thing in our Confluence to XWiki migrator to easily and automatically report which macro parameters we don't handle when converting Confluence macros to equivalent macros in XWiki. This can be used to evaluate the migration quality and spot what can be improved. https://github.com/xwiki-contrib/confluence/blob/7a95bf96787f2fd52a6117a97d4d75d777e08ee1/confluence-xml/src/main/java/org/xwiki/contrib/confluence/filter/internal/macros/TracedMap.java https://github.com/xwiki-contrib/confluence/blob/7a95bf96787...
- IshKebab 1y agoI think if you feel like you need this then it's a bit of a red flag and you should be using Pydantic or `dataclass` instead, then your IDE can statically tell you which fields you don't access (among many other benefits). Dicts are mainly for when you don't know the keys up front.
- mb7733 1y agoStatic analysis could only tell you which fields are never used, across all usage of the class. Not on a given instance.
- taeric 1y agoCounterpoint, something like this for dataclasses would also be very useful. That is, it isn't just knowing whether or not the data is ever used. It is useful to know if it was used in this specific run. And often times, seeing what parts of the data was not used is a good clue as to what went wrong. At the least, you can use it to rule out what code was not hit.
- ok123456 1y agoIf you're inheriting from dict to extend its behavior, there are a lot of side effects with that, and it's recommended to use https://docs.python.org/3/library/collections.html#collections.UserDict https://docs.python.org/3/library/collections.html#collectio... instead.
- quietbritishjim 1y agoFrom right above where you linked to: > The need for this class has been partially supplanted by the ability to subclass directly from dict; however, this class can be easier to work with because the underlying dictionary is accessible as an attribute. Sounds like (unless you need the dict as a separate data member) this class is a historical artefact. Unless there's some other issue you know of not mentioned in the documentation?
- ok123456 1y agodict doesn't follow the usual object protocol, and overloaded methods are runtime dependent. It's only guaranteed that non-overloaded methods are resolved least surprisingly.
- quietbritishjim 1y agoI think you mean overridden (i.e. defined in both base class and derived class) rather than overloaded (i.e. defined more than once in a single place but with different argument types, as least from a typing point of view [1]). Your comment seriously confused me till I figured that out. [1] https://typing.python.org/en/latest/spec/overload.html https://typing.python.org/en/latest/spec/overload.html Even then, to be honest I'm a bit sceptical. Can you point at a link in the official documentation that says overriding methods of dictionaries may not work? I would have thought the link to UserDict would have mentioned that if true. What do you mean they are "runtime dependent"?
- ok123456 1y agoSee Chapter 14 of "Fluent Python", 2nd Edition by Luciano Ramalho. He details this under the heading "Subclassing Built-In Types Is Tricky." UserDict isn't just some historical artifact of a bygone era like some of the posters below are miscorrecing me on.
- quietbritishjim 1y ago
- boothby 1y agoJust a heads up, this fails to track usage of get and setdefault. The ability to iterate over dicts makes the whole question rather murky.
- quietbritishjim 1y agoI 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.
- notatallshaw 1y agosetdefault was a go to method before defaultdict was added to the collections module in Python 2.5, which replaced the biggest use case.
- boothby 1y agoIt'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.
- quietbritishjim 1y agoOne time that defaultdict may come out ahead is if the default value is expensive to construct and rarely needed: d.setdefault(k, computevalue()) defaultdict takes a factory function, so it's only called if the key is not already present: d = defaultdict(computevalue) This applies to some extent even if the default value is just an empty dictionary (as it often is in my experience). You can use dict() as the factory function in that case. But I have never benchmarked!
- masklinn 1y ago
- jgalt212 1y agowhy not inside of __init__ self.accessed_keys = set() instead of @property def accessed_keys(self): return self._accessed_keys
- larrik 1y agoI actually wrote something similar in nodejs for a data import system. Was very handy.
- null_deref 1y agoInteresting! Can you elaborate a little bit more on your implementation?
- larrik 1y agoMine was a bit more specific. I had a JSON object of data exported per account I was importing, and then a complex mapping (also JSON) of where to put each piece of data. Therefore, I really wanted to know that I was actually pulling in all of the data I needed, so I tracked what was seen vs not seen, and compared against what was attempted to see. In the end it was basically a wrapper around the JSON object itself, that allowed lookup of data via a string in "dot notation" (so you could do "keyA.key2" to get the same thing you would have directly in JSON. Then, it would either return a simple value (if there was one), or another instance of the wrapper if the result was itself an object (or an array or wrapped objects). All instances would share the "seen" list. It's unfortunately locked behind NDA/copyright stuff, but the implementation was only 67 lines.
- null_deref 1y agoNice very interesting, thank you very much for taking the time to explain a bit further
- simon04 1y agoVery useful. For configparser.ConfigParser I've found https://stackoverflow.com/a/57307141 https://stackoverflow.com/a/57307141
- golly_ned 1y agoI have a similar use case and this idea also occurred to me. However: the dict in this case would also include dataclasses, and I’d be interested in finding what exact attributes within those dataclasses were accessed, and also be able to mark all attributes in those dataclasses as accessed if the parent dataclasses is accessed, and with those dataclasses, being config objects, being able to do the same to its own children, so that the topmost dictionary has a tree of all accessed keys. I couldn’t figure out how to do that, but welcome to ideas.
- codethief 1y agoOnly tangentially related but I am really excited about PEP 764¹ (inline typed dictionaries). If it gets accepted, we can finally replace entire hierarchies of dataclasses with simple nested dictionary types and call it a day. I am currently teaching (typed) Python to a team of Windows sysadmins and it's been incredibly difficult to explain when to use a dataclass, a NamedTuple, a Pydantic model, or a dictionary. ¹) https://peps.python.org/pep-0764/ https://peps.python.org/pep-0764/
- JohnKemeny 1y agoDo you seriously have difficulties explaining when to use a class and when to use a dictionary?!
- codethief 1y agoYou can create dictionaries on the fly. But dataclass objects require defining that dataclass first. The type safety (and LSP support) story for accessing individual dataclass fields is better than for accessing dict items (sometimes even when they are TypedDicts), but for iterating over all fields it's worse. dataclasses are nominal types and can contain additional logic, TypedDicts are structural ones, overall simpler, can be more convenient and lead to looser coupling. Dataclasses use metaclass and decorator magic while TypedDics are just plain dicts. Etc. Let me make this more concrete: Those sysadmins frequently need to process and pass around complex (as in heavily nested) structured data. The data often comes in the form of singleton objects, i.e. they are built in single place, then used in another place and then thrown away (or merged into some other structure). In other words, any class hierarchy you build represents boilerplate code you'll only ever use once and which will be annoying to maintain as you refactor your code. Do you pick dataclasses or TypedDicts (or something else) for your map data structures? In TypeScript you would just use `const data = <heavily nested object> as const` and be done with it.
- quietbritishjim 1y agoThe line is seriously blurred.
- xg15 1y ago
- nurettin 1y agoAI front: We have models to generate pictures, videos and code. We have the best devs and are so fskin rich! Rust front: Here's a faster ls called ls-rs with different defaults, you should use this! Go front: Here's reverse proxy #145728283 it is an open source project that has slightly different parameters than all the others. Python hobo front: Uhh guys here's a dict that kinda might remember what you've accessed if you used it in a particular way.
- mrits 1y agoFor giant dicts a bloomfilter would work great here
- westurner 1y agoDoes this handle nested dicts (in pickles in sql, which I had to write code to survey one time)? A queue-based traversal has flatter memory utilization for deeply nested dicts than a recursive traversal in Python without TCO. Given a visitor pattern traversal, a visit() function can receive the node path as a list of path components, and update a Counter() with a (full,path,tuple) or "delimiter\.escaped.path" key. Python collections.UserDict implements the methods necessary to proxy the dict Mapping/MutableMapping interface to self.data. For dicts with many keys, it would probably be faster to hook methods that mutate the UserDict.data dict like __setitem__, get, setdefault, update() and maybe __init__() in order to track which keys have changed instead of copying keys() into a set to do an unordered difference with a list. React requires setState() for all mutations this.state because there's no way to hook dunder methods in JS: setState() updates this.state and then notifies listeners or calls a list of functions to run when anything in this.state or when a value associated with certain keys or nested keys in this.state changes. FWIU ipyflow exposes the subscriber refcount/reflist but RxPy specifically does not: ipyflow/core/test/test_refcount.py: https://github.com/ipyflow/ipyflow/blob/master/core/test/test_refcount.py https://github.com/ipyflow/ipyflow/blob/master/core/test/tes... Anyways, For test assertions, unittest.mock MagicMock can track call_count and call_args_list on methods that mutate a dict like __getitem__ and get(). There's also mock_calls, which keeps an ordered list of the args passed: https://docs.python.org/3/library/unittest.mock.html https://docs.python.org/3/library/unittest.mock.html