Skip to content

Instantly share code, notes, and snippets.

@Tarliton
Created January 5, 2018 22:44
Show Gist options
  • Save Tarliton/cdf20e3cd700319517e2a763e8770b11 to your computer and use it in GitHub Desktop.
Save Tarliton/cdf20e3cd700319517e2a763e8770b11 to your computer and use it in GitHub Desktop.
import asyncio
import inspect
from textwrap import dedent
def asynchronize(method):
argspec = inspect.getfullargspec(method)
args = ', '.join(argspec.args)
args_without_self = ', '.join(argspec.args[1:])
source = f"""
async def {method.__name__}_async({args}):
print('before')
await asyncio.sleep(1)
print('after')
return self.{method.__name__}({args_without_self})
amethod = {method.__name__}_async
"""
return source
class Meta(type):
def __new__(meta, classname, bases, classdict):
new_classdict = {}
for k, v in classdict.items():
new_classdict[k] = v
if hasattr(v, '__call__'):
asynchronized = asynchronize(v)
exec(dedent(asynchronized), globals())
new_classdict[f'{v.__name__}_async'] = amethod
return super().__new__(meta, classname, bases, new_classdict)
class Foo(metaclass=Meta):
def calculate(self, a, b):
r = a + b
print(r)
return r
if __name__ == '__main__':
loop = asyncio.get_event_loop()
f = Foo()
loop.run_until_complete(f.calculate_async(1, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment