Reputation: 24007
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?
Upvotes: 15
Views: 6842
Reputation: 20300
If you want to check a socket instance
def is_socket_patched(sock):
return sock.__module__.startswith("gevent")
Upvotes: 0
Reputation: 2010
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"
Upvotes: 22
Reputation: 16935
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']
Upvotes: 8
Reputation: 1628
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
Upvotes: 13