python bijection

Terry Reedy tjreedy at
Fri Nov 20 21:09:41 CET 2009

Joshua Bronson wrote:

> Anyone have any other feedback? For instance, is offering the __call__
> syntax for the inverse mapping wonderful or terrible, or maybe both?

Terrible ;-)

Use standard subscripting with slices, and only that, to both get and set.

Let m[4] == m[4:] == 'abc' # m[4:] is suggested alternative addition
Then m[:'abc'] == 4

m[4:] passes slice(4,None,None) to __getitem__
m[:'abc'] passes slice(None,'abc',None)

It just happens that dict items and slices use the same notation, but 
they do, so take advantage of that. In fact, to emphasize the symmetry 
of the bijective map, consider disallowing m[key] as ambiguous and 
require m[key:], along with m[:key] to access and set.

Note that m[slice(1,2,3):] passes slice(slice(1, 2, 3), None, None), so 
this approach does not even prevent using slices as keys/values.

In __setitem__, m[a:b] which passes slice(a,b,None) would have to be an 
error. In __getitem__, it could either be a error or return True/False 
depending on whether the pair is in the map. But this depends on whether 
__contains__ only tests keys or is modified to test pairs.

Terry Jan Reedy

More information about the Python-list mailing list