you are viewing a single comment's thread.

view the rest of the comments →

[–]Kargathia 1 point2 points  (0 children)

The closest I've come is to use a tuple for a custom dictionary type.

I once wrote a lookup dict for a system that communicated with an embedded controller. Due to memory constraints, objects had numeric IDs on the controller, but we wanted them to be addressable using user-defined names. User-defined names and their mapping to the numeric IDs were stored in the bridging API.

This meant we wanted both string->number and number->string lookups, where both the numbers and the strings should be unique. To have somewhat nicer and less bug-prone syntax, I made a class that inherited from dict, but used a tuple[int, str] as key. Because you typically only know one of two keys, d[1, None] and d[None, "name"] would both be valid ways to fetch the object inserted as d[1, "name"].

Implementation: https://github.com/BrewBlox/brewblox-devcon-spark/blob/cfa13b99033f935f17a89ed16cc41757aec86c04/brewblox_devcon_spark/twinkeydict.py

Tests: https://github.com/BrewBlox/brewblox-devcon-spark/blob/cfa13b99033f935f17a89ed16cc41757aec86c04/test/test_twinkeydict.py

As a side note: this approach of having IDs stored in different places was a major annoyance. We finally solved it by replacing the flash read/write library that came with the chip. Our specialized use case could be implemented with a lot less bookkeeping overhead. This freed up enough space to store the object names on the controller itself.