Java singletonMap in Python
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Sep 23 22:20:34 EDT 2012
On Mon, 24 Sep 2012 00:14:23 +0100, Mark Lawrence wrote:
> Purely for fun I've been porting some code to Python and came across the
> singletonMap[1]. I'm aware that there are loads of recipes on the web
> for both singletons e.g.[2] and immutable dictionaries e.g.[3]. I was
> wondering how to combine any of the recipes to produce the best
> implementation, where to me best means cleanest and hence most
> maintainable. I then managed to muddy the waters for myself by
> recalling the Alex Martelli Borg pattern[4]. Possibly or even probably
> the latter is irrelevant, but I'm still curious to know how you'd code
> this beast.
>
> First prize for the best solution is a night out with me, no guesses
> what the second prize is :)
>
> [1]http://docs.oracle.com/javase/1.4.2/docs/api/java/util/
Collections.html
Copied from that page:
"static Map singletonMap(Object key, Object value)
Returns an immutable map, mapping only the specified key to the specified
value."
I don't see the point of this. It takes a single key, with a single
value, and is immutable so you can't change it or add new keys. What's
the point? Why bother storing the key:value pair in a data structure,
then look up the same data structure to get the same value every time?
# Pseudo-code
d = singletonMap(key, calculate(key))
# later:
value = d[key] # there's only one key this could be
process(value)
Why not just store the value, instead of key, value and mapping?
value = calculate(key)
# later
process(value)
--
Steven
More information about the Python-list
mailing list