Python㧠async def / def 両対å¿ã®ãã³ã¬ã¼ã¿ãæ¸ã
ã¿ã¤ãã«ã®éãã
åç´ã«ä»¥ä¸ã®æ§ãªdecoratorãæ¸ãã¨ãasync defãã©ããã§ããªãã
from functools import wraps from datetime import datetime def timetrack(func): @wraps(func) def inner(self, *args, **kwargs): start = datetime.now() return_value = func(self, *args, **kwargs) end = datetime.now() self.logger.info('%s takes %s sec', func.__name__, (end - start).total_seconds()) return return_value return inner
ãã¨ãã£ã¦æ¬¡ã®ããã«æ¸ãã¨ãä»åº¦ã¯æ®éã®defãåæã«coroutine functionã«ãªã£ã¦ãã¾ã£ã¦å°ãã
from functools import wraps from datetime import datetime def timetrack(func): @wraps(func) async def inner(self, *args, **kwargs): start = datetime.now() return_value = await func(self, *args, **kwargs) end = datetime.now() self.logger.info('%s takes %s sec', func.__name__, (end - start).total_seconds()) return return_value return inner
ãªã®ã§ãasyncio.iscoroutinefunctionã使ã£ã¦ä»¥ä¸ã®ããã«åå²ããã¨ãããã
from functools import wraps from datetime import datetime def timetrack(func): if asyncio.iscoroutinefunction(func): @wraps(func) async def async_inner(self, *args, **kwargs): start = datetime.now() return_value = await func(self, *args, **kwargs) end = datetime.now() self.logger.info('%s takes %s sec', func.__name__, (end - start).total_seconds()) return return_value return async_inner else: @wraps(func) def inner(self, *args, **kwargs): start = datetime.now() return_value = func(self, *args, **kwargs) end = datetime.now() self.logger.info('%s takes %s sec', func.__name__, (end - start).total_seconds()) return return_value return inner
ä¸è¬åããã¦ã¼ãã£ãªãã£ã¿ããã®ãæ¸ããªããã¨ããªãæ°ããããã©ãä»åããã¾ã§ã®ã¢ããã¼ã·ã§ã³ã¯ãªãã