gpt4 book ai didi

python - python 中的猴子修补 : When we need it?

转载 作者:太空宇宙 更新时间:2023-11-03 12:50:13 24 4
gpt4 key购买 nike

在 Python 中,术语 monkey patch 仅指在运行时动态修改类或模块,作为初学者,我真的很难在 python 上下文中理解这个术语。谁能用真实世界的例子向我解释我们到底是怎么做的?

  1. 类的动态修改
  2. 运行时动态修改模块

我坚持要用一个真实世界的例子(尽可能简单)来理解我们必须在哪些场景下完成这样的任务?

最佳答案

Monkey-patching 是一种以现有代码将继续运行但具有修改后的行为的方式进行某些全局底层更改的方法。

改变内置 str 命令行为的一个非常简单的例子:

b.py

def foo(msg):
s = str(msg)
print s, type(s)

a.py

import b

b.foo('foo')

# monkey-patch
import __builtin__
__builtin__.str = unicode

b.foo('foo')

# Results:
#foo <type 'str'>
#foo <type 'unicode'>

a 模块修改了使用 str 命令的其他代码的行为,将其修补为使用 unicode。这是必要的,因为我们假装我们无法访问 b.py 的代码。它可能是一个巨大的包,我们只是使用并且无法更改。但是我们可以插入要调用的新代码来改变行为。

真实世界的例子from gevent

>>> import gevent
>>> from gevent import socket
>>> urls = ['www.google.com', 'www.example.com', 'www.python.org']
>>> jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls]
>>> gevent.joinall(jobs, timeout=2)
>>> [job.value for job in jobs]
['74.125.79.106', '208.77.188.166', '82.94.164.162']

The example above used gevent.socket for socket operations. If the standard socket module was used it would took it 3 times longer to complete because the DNS requests would be sequential. Using the standard socket module inside greenlets makes gevent rather pointless, so what about module and packages that are built on top of socket?

That’s what monkey patching for. The functions in gevent.monkey carefully replace functions and classes in the standard socket module with their cooperative counterparts. That way even the modules that are unaware of gevent can benefit from running in multi-greenlet environment.

>>> from gevent import monkey; monkey.patch_socket()
>>> import urllib2 # it's usable from multiple greenlets now

关于python - python 中的猴子修补 : When we need it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11977270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com