RepugNaNt [entries|reading|network|archive]
simont

[ userinfo | dreamwidth userinfo ]
[ archive | journal archive ]

Wed 2011-12-07 15:45
RepugNaNt
LinkReply
[personal profile] fanfWed 2011-12-07 16:45
if dictionary.get(key, not value) == value:
Link Reply to this | Thread
[personal profile] simontWed 2011-12-07 16:53
Ooh, neat!

I did consider using a transformed version of value, e.g. value+1 if it was an integer or value+"x" if a string, but in each of those cases I couldn't see any reason you'd do that – if you knew the type of value anyway, it would be easier to just compare it against some constant thing not of that type.

But it hadn't occurred to me that not value would apply to all types. Cunning.
Link Reply to this | Parent | Thread
[identity profile] cartesiandaemon.livejournal.comWed 2011-12-07 17:03
Yeah. I considered that, if the function is parameterised by the type of value, you could have a meta-type, but I didn't expect to think of anything neat. Thinking about it, the tricky (but not very efficient) way would be to have a vector (or any other container type) containing value (assuming python doesn't support vectors nested infinitely deep :))

But "not" is very good. Are there any weird edge cases? :)
Link Reply to this | Parent | Thread
[personal profile] fanfWed 2011-12-07 17:08
It doesn't fix the NaN <> NaN problem :-)
Link Reply to this | Parent
[identity profile] ptc24.livejournal.comWed 2011-12-07 17:13
Not _quite_ equivalent to what simont had originally:
>>> class foo:
...   def __cmp__(self, other):
...     if other is True: return 0
...     if other is False: return 0
...     return 1
... 
>>> f = foo()
>>> g = foo()
>>> f == g
False
>>> d = {}
>>> d[5] = f
>>> d.get(6, not f) == f
True
>>> 6 in d and d[6] == f
False

Note cmp is -1,0,1 for less than/equal/greater than.
Link Reply to this | Parent | Thread
[personal profile] fanfWed 2011-12-07 17:46
If you abuse semantics like that you deserve to lose :-)
Link Reply to this | Parent | Thread
[personal profile] simontWed 2011-12-07 18:10
Yes, I think that clever as [livejournal.com profile] ptc24's counterexample is (and doubly so because I tried to construct a similar thing and didn't quite get it to work), it falls into the same category as [livejournal.com profile] cartesiandaemon's question about NaN: if you define a class which has deliberately weird behaviour when compared, then you've violated the warranty of any of these methods once you try to use an instance of that class as a key or value in the dictionary or as a key or value to test for. It's only fair game to use it as the dummy non-value.
Link Reply to this | Parent
navigation
[ go | Previous Entry | Next Entry ]
[ add | to Memories ]