How to choose asynchronous or synchronous method variants in python?

后端 未结 1 343
后悔当初
后悔当初 2020-12-11 12:45

Let\'s assume I have a class that is used to perform I/O operations:

class CommunicationStack:
    def __init__(self, socket):
        self.socket = socket

         


        
相关标签:
1条回答
  • 2020-12-11 13:16

    If you want to call async functions same way as regular ones, you may be interested in using gevent.

    asyncio wants you to explicitly mark functions as async and to explicitly use await everywhere async stuff happens. In other words asyncio wants you to have different interfaces for sync and async code.

    This is intentional decision made to fight with concurrency problems which is much harder to achieve when async nature of a code is hidden (like in gevent).

    So yes - two different independent AsyncCommunicationStack and CommunicationStack classes is a way to go if you want to support both worlds. Although once you have async version you can cast write critical code with it and make it sync just running it with asyncio.run(). Problem only is that you won't be able to return to async world after that.

    0 讨论(0)
提交回复
热议问题