[Tutor] Using type
Dave Angel
d at davea.name
Fri Aug 12 11:08:26 CEST 2011
On 08/12/2011 03:47 AM, Alan Gauld wrote:
> 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
>
>
This is exactly the way I'd think about this problem. But I'd also
point out the differences between the three.
if type(x) == list
is the most concise way to express the original relationship.
if you want to be able to also handle any type that's derived from list,
use isinstance().
If you want to be able to handle any iterable, use the final form.
It'll work on lists and tuples, for simple examples. But beware that
when you iterate through strings, the individual characters are also
strings, and this function will fail with an error like:
RuntimeError: maximum recursion depth exceeded
--
DaveA
More information about the Tutor
mailing list