Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python equivalence of default in C#

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.

like image 805
Nix Avatar asked Dec 06 '22 20:12

Nix


2 Answers

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.

like image 82
Thomas K Avatar answered Dec 23 '22 21:12

Thomas K


How about:

type(myObj)()

It works for int and dict.

like image 41
SiggyF Avatar answered Dec 23 '22 20:12

SiggyF