Question

When using the package pygal, I have to change a utility function in pygal.util module. This function is called by other functions in other modules. How do I monkey-patch this function? Right now, I've edited the code in dist_packages but there must be a way to dynamically assign to this function?

The function is pygal.util.is_major. I tried to do it the following way: pygal.util.is_major = lambda x: False But it doesn't work. I think it's because the other modules in the package are importing this function into their local namespace. So me changing it has no effect since the older version of the function was already imported by the other modules into their local namespace.

Was it helpful?

Solution

The reason assigning to is_major doesn't work is because two other pygal modules import is_major into their local namepace before you assign to it.

The pygal.graph.radar module:

from pygal.util import deg, cached_property, compute_scale, is_major

And the pygal.graph.graph module:

from pygal.util import (
    is_major, truncate, reverse_text_len, get_texts_box, cut, rad, decorate)

If you can monkey path the is_major function before importing either of those modules, it should work. If you can't, you may be able to reload the graph modules after monkey patching.

Something like this:

import pygal.util
import pygal.graph
import pygal.graph.radar

pygal.util.is_major = my_function
reload(pygal.graph)
reload(pygal.graph.radar)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top