Getting default values of any type in Python3

69 views Asked by At

Assuming I want to make a function in python that just returns the default value of a given type as a parameter:

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

For example if I got type of list that It should return an empty list. If I got a string as a type it should return "". If I got an integer as a type it should return 0.

1

There are 1 answers

1
Moaybe On BEST ANSWER
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)