![](/img/trans.png)
[英]How to do 'generic type hinting' of functions (i.e 'function templates') in Python?
[英]How do I add default parameters to functions when using type hinting?
如果我有這樣的功能:
def foo(name, opts={}):
pass
我想給參數添加類型提示,我該怎么做? 我假設的方式給了我一個語法錯誤:
def foo(name: str, opts={}: dict) -> str:
pass
以下不會引發語法錯誤,但它似乎不是處理這種情況的直觀方法:
def foo(name: str, opts: dict={}) -> str:
pass
我在typing
文檔或 Google 搜索中找不到任何內容。
編輯:我不知道 Python 中的默認參數是如何工作的,但是為了這個問題,我將保留上面的示例。 一般來說,最好執行以下操作:
def foo(name: str, opts: dict=None) -> str:
if not opts:
opts={}
pass
我最近看到了這個單行:
def foo(name: str, opts: dict=None) -> str:
opts = {} if not opts else opts
pass
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.