Reputation: 1885
At work we're using gevent to create some asynchronous servers, and there's some debate about when to perform monkey patching in relation to other modules. The gevent documentation shows things like this:
from gevent import monkey
monkey.patch_socket()
import socket
Where the monkey patching happens before the library modules have been imported.
However, my manager feels the order of monkey patching should be this:
import socket
from gevent import monkey
monkey.patch_socket()
Where monkey patching is called after the library module is imported. Which makes it look like monkey patching sees the socket module has been imported, and patches it at that point.
I've found some discussions that say do it one way, and others that say to do it the other. My own simple testing seems to say it doesn't matter. I am seeking opinions on this, with some clear reasons why, or references that would say why.
Upvotes: 1
Views: 3566
Reputation: 586
As the current maintainer of gevent, I will point to the documentation which specifically says (multiple times) that the recommended way to monkey-patch is to do it as early as possible, and preferably before any other imports.
Now, with most standard library modules you can get away with monkey-patching after they're imported. But third-party libraries are not necessarily safe that way. In general, it's just safer and reduces trouble to monkey-patch ASAP.
Upvotes: 1
Reputation: 22982
Well, according to the source code (see bellow) patch_socket
calls patch_module
which imports the socket
module for you.
def patch_module(name, items=None):
gevent_module = getattr(__import__('gevent.' + name), name)
module_name = getattr(gevent_module, '__target__', name)
module = __import__(module_name)
if items is None:
items = getattr(gevent_module, '__implements__', None)
if items is None:
raise AttributeError('%r does not have __implements__' % gevent_module)
for attr in items:
patch_item(module, attr, getattr(gevent_module, attr))
return module
See that in gevent
repository on GitHub.
So, you don't need to import socket at all (unless you use it of course).
Upvotes: 0