How to generalize a function call which may be async, tornado coroutine, or normal?
<p>I have an application which has a library in multiple configurations:</p>

<ul>
<li>Python2.7 native</li>
<li>Python2.7 tornado</li>
<li>Python3.5 asyncio</li>
</ul>

<p>Currently, I have code that is nearly identical against all three, but there are minor differences in how each function call are invoked. This means I have a ton of code duplication, because I have stuff like the following in many places:</p>

<pre><code>#Python2.7native.py
def main(client):
   client.foo(args)
   client.bar(args)

#Python2.7tornado.py
@gen.coroutine
def main(client):
    yield client.foo(args)
    yield client.bar(args)

#Python3.5asyncio.py
async def main(client):
    await client.foo(args)
    await client.bar(args)
</code></pre>

<p>where <code>client</code> is a language specific implementation, supporting native python, asyncio, and tornado respectively. The API method calls are identical.</p>

<p>I am hoping to be able to somehow generalize this into a single method I can include in a shared file, which appropriately calls the various methods</p>

<p>I've thought about defining the methods in a separate file and using <code>getattr</code> to invoke the test properly, but this seems really messy.</p>

<p>Is there a good way to do this?</p>

<p>Use <code>@gen.coroutine</code> and <code>yield</code>: This will work in all Python versions. A function decorated with <code>gen.coroutine</code> is a little slower than a native coroutine, but can be used in all the same scenarios.</p>

<p>For the synchronous case, use <code>run_sync</code>:</p>

<pre><code>result = IOLoop.current().run_sync(main)
</code></pre>

python python-2.7 tornado python-3.5 python-asyncio