I have a method that takes (among others) a dictionary as an argument. The method is parsing strings and the dictionary provides replacements for some substrings, so it doesn't have to be mutable.
This function is called quite often, and on redundant elements so I figured that caching it would improve its efficiency.
But, as you may have guessed, since dict
is mutable and thus not hashable, @functools.lru_cache
can't decorate my function. So how can I overcome this?
Bonus point if it needs only standard library classes and methods. Ideally if it exists some kind of frozendict
in standard library that I haven't seen it would make my day.
PS: namedtuple
only in last resort, since it would need a big syntax shift.
namedtuple
and add access byx["key"]
? This will probably be just a few lines of code.collections.namedtuple
which returns atype
, so if I want to add a__getitem__
to a named tuple I'd have to do it dynamically, which shouldn't be possible, and even if it is is really ugly. Is there another way to do this?namedtuple()
:class X(namedtuple("Y", "a b c")): ...
.