mutable numeric type

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Jan 2 02:15:18 EST 2007


On Mon, 01 Jan 2007 19:20:21 -0800, Andreas Beyer wrote:

> I am using a third party library that is performing basic numerical 
> operations (adding, multiplying, etc.) with objects of unknown type. Of 
> course, the objects must support the numerical operators. In my case the 
> third party library is a graph algorithm library and the assigned 
> objects are edge weights. I am using the library to compute node 
> distances, etc.
> 
> I would like to be able to change the edge weights after creating the 
> edges. Otherwise, I would have to remove the edges and re-create them 
> with the new values, which is quite costly.

You've measured it or you're guessing?

Presumably the edges and/or nodes store the weights somewhere. Why not
just reassign the weight directly in place?

It isn't easy to judge whether your scheme is good bad or indifferent when
we know so little about the graph library you are using.


> Since I also didn't want to change the code of the graph library, 

You could subclass the graph class.

Another possibility is to dynamically modify the library, without changing
its source code. E.g.


from GraphLibrary import GraphWalker as _gw
import GraphLibrary

def myGraphWalker(args):
    x = _gw(args)
    do_something_to(x)
    return x

GraphLibrary.GraphWalker = myGraphWalker
# now use GraphWalker as normal, except it has your 
# code instead of the original

This works for class methods as well.


> I came up with a mutable numeric 
> type, which implements all the numerical operators (instances are of 
> course not hashable). This allows me to change the edge weights after 
> creating the graph.

This is another alternative, although I still don't understand why you
can't just reassign the weights in place.


-- 
Steven D'Aprano 




More information about the Python-list mailing list