Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isinstance(x, list) when iterating a list containing strings and lists

At Iterating nested list inside-out, I was told that "type-checking isn't Pythonic". Generally, this is true: we want to look only at the interface (duck-typing) rather than a specific type.

The question asks about nested lists of the form ['a', ['c', ['e'], 'd'], 'b'], and we specifically consider strings atomic (non-iterable). So, we can't use a blanket collections.Iterable, but on the other hand isinstance(x, list) does seem a bit hacky.

My answer was

def traverse(l):
    for x in l:
        if isinstance(x, list):
            traverse(x)
    callback(l)

What's a better approach? Or is isinstance OK here?

like image 476
nneonneo Avatar asked Feb 19 '13 15:02

nneonneo


People also ask

What is isinstance() function in Python?

Python isinstance() Function The isinstance() function returns True if the specified object is of the specified type, otherwise False . If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.

Should you use Isinstance Python?

If you need to check the type of an object, it is recommended to use the Python isinstance() function instead. It's because isinstance() function also checks if the given object is an instance of the subclass.

How do you know if something is a tuple or a list?

Use isinstance() to check the data type of a variable in Python. Use isinstance(var, class) with var as the variable to compare and class as either list or tuple to determine if obj is a list or a tuple. isinstance(var, class) returns True if var is of type class and False otherwise.


1 Answers

I think that your answer is OK here -- Although I might change it to

if not isinstance(x,basestring):
   ...

to make it a little more accepting depending on the expected input. Ultimately, some problems you need isinstance which is why it still exists in the language.

That being said, the thing about this problem that is un-pythonic is the data-structure. In python, if a problem seems really hard, it probably means you're storing the data in the wrong way ... (Of course, I realize that you had no control over what the original poster of the other question's data structure was ;-).

Basically, I guess that my view is that isinstance is the hack that you need to make lemonade when your colleagues/some library writer somewhere gives you lemons -- Otherwise you avoid it where possible.

like image 113
mgilson Avatar answered Sep 18 '22 19:09

mgilson