import asyncio class MyLogger: enabled = True def log(self, something: str) -> None: if not self.enabled: print("NOT LOGGING:", something) return print(something) class SilenceLogs: def __enter__(self): MyLogger.enabled = False def __exit__(self, exc_type, exc_val, exc_tb): MyLogger.enabled = True class AsyncSilenceLogs: async def __aenter__(self): MyLogger.enabled = False async def __aexit__(self, exc_type, exc_val, exc_tb): MyLogger.enabled = True async def log_after_1_sec(something: str) -> None: await asyncio.sleep(1) MyLogger().log(f'{something} after 1 second') async def suppressed_logging_after_2_sec(something: str) -> None: await asyncio.sleep(1) with SilenceLogs(): await log_after_1_sec(something) async def async_suppressed_logging_after_2_sec(something: str) -> None: await asyncio.sleep(1) async with AsyncSilenceLogs(): await log_after_1_sec(something) async def main() -> None: print("should -> should not") await asyncio.gather( log_after_1_sec("Should be logged"), suppressed_logging_after_2_sec("Should not be logged"), ) print("should not -> should") await asyncio.gather( suppressed_logging_after_2_sec("Should not be logged"), log_after_1_sec("Should be logged"), ) print("[async] should -> should not") await asyncio.gather( log_after_1_sec("Should be logged"), async_suppressed_logging_after_2_sec("Should not be logged"), ) print("[async] should not -> should") await asyncio.gather( async_suppressed_logging_after_2_sec("Should not be logged"), log_after_1_sec("Should be logged"), ) loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.stop()