what benefit does isinstance give over type()? I'm not arguing, I'm asking.
Personally I think: if isinstance(obj, (tuple,list)): is more confusing (especially for newcomers) than: if type(obj) in (types.ListType, types.TupleType):
isinstance will also return True if obj is a sublcass of tuble or list. It is usually considered safer to use isinstance unless you know for sure that the type will be a tuple or list and not a sublcass of those.
In general, isinstance(foo, klass) returns True if foo is an instance of klass or a subclass of it. It can also accept types.* instead of classes. Martelli calls it the lesser of two evils. :-)
Comment
Why use type() instead of isintance()?
Replies
what benefit does isinstance give over type()? I'm not arguing, I'm asking.
Personally I think:
if isinstance(obj, (tuple,list)):
is more confusing (especially for newcomers) than:
if type(obj) in (types.ListType, types.TupleType):
isinstance will also return True if obj is a sublcass of tuble or list. It is usually considered safer to use isinstance unless you know for sure that the type will be a tuple or list and not a sublcass of those.
That is very useful to know! Thank you.
In general, isinstance(foo, klass) returns True if
foo is an instance of klass or a subclass of it. It can also accept types.* instead of classes. Martelli calls it the lesser of two evils. :-)
It's just a of an oddity in python that 'list' is a type object and not a <type 'function'> like one'd expect it to be.