获取Python3中任意类型的默认值

问题描述 投票:0回答:1

假设我想在 python 中创建一个函数,只返回给定类型的默认值作为参数:

def PrintDefaultValue(valueType: type):
   print(default(type)) // ?? # <-- how I get that with a type instance

例如,如果我得到列表类型,它应该返回一个空列表。 如果我得到一个字符串作为类型,它应该返回“”。 如果我得到一个整数作为类型,它应该返回 0。

python python-3.x types default-value
1个回答
0
投票
from collections import defaultdict

def PrintDefaultValue(valueType: type):
    default_values = defaultdict(
        lambda: None,  # Default factory for unknown types
        {int: 0, float: 0.0, str: "", list: [], dict: {}, bool: False}
    )
    
    default_value = default_values[valueType]
    print(default_value)
© www.soinside.com 2019 - 2024. All rights reserved.