3 ms·
Several times, when working with Lua, I’ve made what I call “Janus tables”. Give them a string, they return a table or function. Give them the table or functio
by samatman 8y ago
Several times, when working with Lua, I’ve made what I call “Janus tables”.
Give them a string, they return a table or function. Give them the table or function, they return a string.
It’s a useful technique that you can only apply if your hashmap can map anything to anything.
- BurningFrog 8y agohttps://en.wikipedia.org/wiki/Bidirectional_map https://en.wikipedia.org/wiki/Bidirectional_map Any hashmap will have problems with storing mutable objects, where the hash value itself can change after the object has been stored, causing some very unwanted paradoxes. And that is the problem with Python dicts as keys.
- marcianx 8y agoI don't think mutability is a concern if your goal is to get a bidi map between strings and (mutable) _instances_; i.e. if you just want to use the reference to the dict itself as the hash rather than the contents of the dict itself.
- BurningFrog 8y agoYeah, I don't actually know if Python computes hashes for dicts by content or "identity". I just assumed it was the former, based on the fact that dicts are disallowed as keys.
- fiddlerwoaroof 8y agoIt’s been a while, but I’m pretty sure the reason why a dictionary can’t have a dictionary as it’s key is because the dictionary class doesn’t implement the __hash__ method that would compute the hashcode.
- np_tedious 8y agoThis is definitely the proximate reason. The reason for that choice is because the object is mutable.
- fiddlerwoaroof 8y agoSure, but as others have mentioned, you can make your own choice by subclassing dict and defining your own hash function, as long as that function is defined in a way that follows the appropriate rules.
- CydeWeys 8y agoWhat's a use case for needing to be able to do this?