我正在开发一个使用
我喜欢
比如,我写了下面这样的代码:
```python async def foo(): await asyncio.sleep(1) ```
那么,其他人能在3.4版本中使用它吗?
asyncio
的Python聊天机器人框架。但是我看到了PEP-492,其中有一种新的语法:async
/await
,并且最终被接受了。我喜欢
async
/await
语法,并想要使用它。但我担心它是否向后兼容3.4版本。比如,我写了下面这样的代码:
```python async def foo(): await asyncio.sleep(1) ```
那么,其他人能在3.4版本中使用它吗?
import asyncio
class ChatBot:
def __init__(self, loop):
self.loop = loop
async def connect(self):
self.reader, self.writer = await asyncio.open_connect(HOST, PORT, loop=self.loop)
async def read():
return await self.reader.read()
async def run(self):
running = True
while running:
try:
await self.connect()
line = await self.read()
if not line:
continue
await self.parse(line)
except BotInternalError as e:
if e.stop:
running = False
break
except:
pass
async def parse(self, msg):
if msg.startswith('PING'):
self.pong()
elif msg.startswith('ERROR'):
self.error()
else:
await self.some_work(msg)
async def some_work(self, msg):
# some looooooooong works
self.send(msg)
def send(self, msg):
self.writer.write(msg)
然后,我可以在py35中使用它与这个源代码。
loop = asyncio.get_event_loop() # I don't know it really needed in py35.
bot = ChatBot(loop)
asyncio.run_until_complete(bot.run())
但是,py34没有await
语法。如果我在PyPI上上传了上述源码且没有版本约束,并且有人在py34上安装了它,它会正常工作吗?我该如何保证它的兼容性?
@asyncio.coroutine
描述为“老的”构造方式,实际上这种构造方式只在最近的 Python 版本中出现,这让人感到有趣。 :-) - Mark Dickinson