Created
January 5, 2018 22:44
-
-
Save Tarliton/cdf20e3cd700319517e2a763e8770b11 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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