Modifying the {} and [] tokens

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Sep 8 14:24:43 CEST 2003


mwilson at the-wire.com (Mel Wilson) wrote in news:oQhU/ks/KXNd089yn at the-
wire.com:

>    Personally, the applications I've written so far would
> like dictionary addition d+u to work like
> 
>         for k in u.keys():
>             d[k] = d.get (k, additive_identity) + u[k]
> 
> where additive_identity is a magical value that's 0 working
> with numbers, [] with lists, () with tuples and '' with
> strings.  In real life I'd catch the key errors instead.

FWIW, Your 'magical value' isn't actually terribly magical, it is easily 
defined with a few lines of Python:

>>> class AdditiveIdentityClass:
	def __coerce__(self, other):
		return type(other)(), other

	
>>> additive_identity = AdditiveIdentityClass()
>>> additive_identity + 42
42
>>> additive_identity + "urk!"
'urk!'
>>> additive_identity + (1,2,3)
(1, 2, 3)
>>> additive_identity + { 1:0 }
Traceback (most recent call last):
  File "<pyshell#34>", line 1, in ?
    additive_identity + { 1:0 }
TypeError: unsupported operand types for +: 'dict' and 'dict'
>>> [ 5 ] + additive_identity
[5]
>>> 3 - additive_identity
3

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list