gevent monkey patching order
<p>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:</p>

<pre><code>from gevent import monkey
monkey.patch_socket()
import socket
</code></pre>

<p>Where the monkey patching happens before the library modules have been imported. </p>

<p>However, my manager feels the order of monkey patching should be this:</p>

<pre><code>import socket
from gevent import monkey
monkey.patch_socket()
</code></pre>

<p>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.</p>

<p>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. Does anyone have an opinion on this, with some clear reasons why, or references that would say why?</p>

<p>Thanks in advance!!
Doug</p>

<p>Well, according to the source code (see bellow) <code>patch_socket</code> calls <code>patch_module</code> which imports the <code>socket</code> module for you.</p>

<pre><code>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
</code></pre>

<p>See that in <code>gevent</code> repository on GitHub.</p>

<p>So, you don't need to import socket at all (unless you use it of course). </p>

python gevent monkeypatching