Why monkey patching on module object doesn't work ?

Ian Kelly ian.g.kelly at gmail.com
Thu Aug 18 01:00:51 EDT 2016


On Wed, Aug 17, 2016 at 10:14 PM, Shiyao Ma <i at introo.me> wrote:
> Hi,
>
> I am using Python2.
>
> For the following snippet,
>
> http://ideone.com/i36pKO
>
> I'd suppose the dummy_func would be invoked, but seems not.
>
> Indeed, heapq.heapify does invoke cmp_lt per here:
> https://hg.python.org/cpython/file/2.7/Lib/heapq.py#l136
>
> So why this way of monkey patching failed?

Because of this:
https://hg.python.org/cpython/file/2.7/Lib/heapq.py#l351

When you call heapq.heapify, it's not actually calling the reference
implementation in that file. It's actually calling a C implementation
that totally ignores everything in that module.

If you really want to do this, you can disable the C implementation by
adding this before importing heapq:

import sys
sys.modules['_heapq'] = None

This marks the _heapq module as not found in the module cache, which
prevents he module loader from trying to import it, resulting in heapq
using the reference implementation instead.

I don't recommend doing this, however. You'd be disabling the more
efficient implementation in order to monkey-patch an undocumented
function that should be considered an implementation detail. For
example, that cmp_lt function doesn't even exist in Python 3:
https://hg.python.org/cpython/file/tip/Lib/heapq.py



More information about the Python-list mailing list