Two mappings inverse to each other: f, g = biject()

Jonathan Fine jfine at pytex.org
Tue Feb 6 05:22:28 EST 2007


Hello

As part of the MathTran project I found myself
wanting to maintain a bijection between long
names and short names.
   http://www.open.ac.uk/mathtran

In other words, I wanted to have two dictionaries
f and g such that
   f[a] == b
   g[b] == a
are equivalent statements.

A google search for biject.py and bijection.py
produced no hits, so I suspect that this may not
have been done before.

I've written a partial implementation of this,
and would appreciate comments.

http://texd.cvs.sourceforge.net/texd/tex/util.py?revision=1.1&view=markup
http://texd.cvs.sourceforge.net/texd/test_tex/test_util.py?revision=1.1&view=markup

Here's the code from test_util.py, that shows how it
works.  The weakref stuff is so that there isn't a
circular reference f to g to f.
===
from tex.util import biject

f, g = biject()
assert f.inverse is g
assert g.inverse is f

f[1] = 2
assert f[1] == 2
assert g[2] == 1
assert f.has_value(2)

import weakref

wr_g = weakref.ref(g)
del g
assert wr_g() == None
assert f.inverse == None
===

best regards


Jonathan




More information about the Python-list mailing list