[爆卦]python return用法是什麼?優點缺點精華區懶人包

為什麼這篇python return用法鄉民發文收入到精華區:因為在python return用法這個討論話題中,有許多相關的文章在討論,這篇最有參考價值!作者shiyeh (shiyeh)看板Python標題[問題] yield跟return時間Tue ...


最近看fastapi常常看到類似這段code

def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

想請問為什麼db 是yield出來,而不是用return就好啊?

跟使用情境有關嗎?
之前也有在for迴圈之類的 看過這個用法

用yield的用意是什麼呢?

--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.167.217.119 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1647356283.A.CF3.html
lycantrope: 這邊用return的話db.close()會在return 之前執行 03/15 23:15
lycantrope: yield只是暫時跳出function回傳,之後還會跳回來執行 03/15 23:16
lycantrope: db.close() 03/15 23:16
TuCH: 我也很好奇 fastapi 什麼時候會進finally: db.close 03/16 09:02
lycantrope: get_db StopIteration 或是被del 都會執行finally 03/16 09:56
lycantrope: 有點類似另類的context manager 覺得酷可以學起來w 03/16 09:58
poototo: with的一種語法糖 03/16 10:48
TuCH: 我覺得fastapi 的 Depends 也是蠻神奇的 也是不知道怎麼進 03/16 12:51
hanfadacai: 這個之前有用到 但後來用忘記用法 只知道跟return很像 03/17 17:48
single4565: https://youtu.be/x6MNOSRY5EM 03/19 15:16
single4565: 可能幫助 03/19 15:16
mantour: try: ... finally: ... 才是比較基本的寫法吧? with 應 03/23 00:47
mantour: 該是後來才加進去的語法(PEP 343) 03/23 00:47

你可能也想看看

搜尋相關網站