Is there a way in python to get a types default value?
//C#
default(typeof(int))
I am looking for a more pythonic way to get type defaults?
#python
if(isinstance(myObj, int):
return 0
elif(isinstance(myObj, dict):
return {}
else:
return None
Obviously I dumbed it down. I am dealing with some abstract things, and when someone asks for an attribute I don't have, I basically check a mapping of key->type and return a default instance with a classic switch.
Just instantiate it:
int() # 0
dict() # {}
list() # []
More detail: there's no explicit concept of a 'default value' in Python. There's just an instance of the class instantiated with the default parameters. Some classes may expect arguments when you instantiate them, in which case there isn't really a default value.
How about:
type(myObj)()
It works for int and dict.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With