[Tutor] Using type
Alan Gauld
alan.gauld at btinternet.com
Fri Aug 12 09:47:08 CEST 2011
On 12/08/11 07:04, Emeka wrote:
> Hello All,
>
> I need help here, type(item) == [].__class__:. What is the idiomatic way
> of doing it?
if type(item) == type([])...
or in this case
if type(item) == list...
But probably preferrable to using type is to use isinstance:
if isinstance(item, list)...
And even more preferable still is don't check the type at
all but just try the operation
try:
item.doSomething()
except AttributeError:
doSomethingElse(item)
But that isn't always appropriate.
> def myflatten(my_data):
> gut = []
> for item in my_data:
> if type(item) == [].__class__:
> gut = gut + myflatten ( item)
> else:
> gut.append(item)
> return gut
In this particular case you presumably want to be
able to use any iterable object as an argument.
So it might be better written as:
def myflatten(my_data):
gut = []
for item in my_data:
try:
iter(item) # test for iterability
gut = gut + myflatten(item)
except TypeError:
gut.append(item)
return gut
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list