Python-猴子补丁失败,为什么? [英] Python - monkey patch fails, why?

查看:161
本文介绍了Python-猴子补丁失败,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过已安装的模块在f(*args, **kwargs)上安装猴子补丁.我在自己的代码上使用了decorator的想法,但是已安装模块中的其他方法无法正确调用f.

I want to monkey patch on f(*args, **kwargs) from an installed module. I use the idea of decorator on my own code, but other methods from the installed module fails to call f correctly.

这里是一个例子:

import numpy as np

def log(func):
    def wrapper(*args, **kwargs):
        print('logging')
        return func(*args, **kwargs)
    return wrapper

if __name__ == "__main__":
    a1 = np.asarray([0, 1, 2])
    print(f'a1={a1}')

    a2 = np.array([0, 1, 2])
    print(f'a2={a2}')

    np.array = log(np.array)

    a3 = np.asarray([0, 1, 2])
    print(f'a3={a3}')

    a4 = np.array([0, 1, 2])
    print(f'a4={a4}')

输出为:

a1=[0 1 2]
a2=[0 1 2]
a3=[0 1 2]
logging
a4=[0 1 2]

我希望结果是:

a1=[0 1 2]
a2=[0 1 2]
logging
a3=[0 1 2]
logging
a4=[0 1 2]

因为asarray在源代码中调用array.

我的问题是: 1.为什么猴子补丁失败? 2.如何解决?

My questions are: 1. Why monkey patch fails? 2. How to fix it?

推荐答案

通过np.array = log(np.array)您正在更改np.array的公共"名称所指的功能.

By np.array = log(np.array) you are changing which function the "public" name np.array refers to.

但是np.asarray是在

But np.asarray is defined in the numpy.core.numeric module, which has its own "private" name to refer to that function. It is not affected by patching the public name.

您必须修补私人名称:

np.core.numeric.array = log(np.array)

这篇关于Python-猴子补丁失败,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆