I have a Python unittest that depends on multiprocessing
and therefore must not run when Gevent's monkey-patching is active. Is there a Python statement that can tell me whether gevent.monkey.patch_all
has run or not?
A monkey patch is a way to change, extend, or modify a library, plugin, or supporting system software locally. This means applying a monkey patch to a 3rd party library will not change the library itself but only the local copy of the library you have on your machine.
Overview. gevent is a coroutine-based cooperative multitasking python framework that relies on monkey patching to make all code cooperative. Gevent actually draws its lineage from Eve Online which was implemented using Stackless Python which eventually evolved into eventlet which inspired gevent.
Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time.
In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time. We use above module (monk) in below code and change behavior of func() at run-time by assigning different value.
I'm not sure there is an idiomatic way, but one simple way would be to check the socket.socket
class:
import gevent.monkey, gevent.socket
gevent.monkey.patch_all()
import socket
if socket.socket is gevent.socket.socket:
print "gevent monkey patch has occurred"
afaik the gevent.monkey.saved
dict is only updated when an item is patched, and the original is placed within the dict (and removed on unpatching), e.g.
>>> from gevent.monkey import saved
>>> 'sys' in saved
True
Here's what I used for detecting if gevent monkey patching is active.
def is_gevent_monkey_patched():
try:
from gevent import monkey
except ImportError:
return False
else:
return bool(monkey.saved)
As A. Jesse Jiryu Davis mentioned, this works for gevent 1.0.x only.
Updated: in gevent 1.1 there's an support API that is helpful to know if objects have been monkey-patched. So the answer for gevent 1.1 could be:
def is_gevent_monkey_patched():
try:
from gevent import monkey
except ImportError:
return False
else:
return monkey.is_module_patched('__builtin__')
BTW, I find that monkey.is_module_patched('sys')
always returns False
. By looking into monkey.saved.keys()
after running monkey.patch_all()
, I think only the following modules are valid to check:
['_threading_local', '_gevent_saved_patch_all', 'socket', 'thread', 'ssl',
'signal', '__builtin__', 'subprocess', 'threading', 'time', 'os', 'select']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With