In Python, how do I determine if an object is iterable?

前端 未结 21 2227
太阳男子
太阳男子 2020-11-22 00:35

Is there a method like isiterable? The only solution I have found so far is to call

hasattr(myObj, \'__iter__\')

But I am not

21条回答
  •  囚心锁ツ
    2020-11-22 00:50

    Instead of checking for the __iter__ attribute, you could check for the __len__ attribute, which is implemented by every python builtin iterable, including strings.

    >>> hasattr(1, "__len__")
    False
    >>> hasattr(1.3, "__len__")
    False
    >>> hasattr("a", "__len__")
    True
    >>> hasattr([1,2,3], "__len__")
    True
    >>> hasattr({1,2}, "__len__")
    True
    >>> hasattr({"a":1}, "__len__")
    True
    >>> hasattr(("a", 1), "__len__")
    True
    

    None-iterable objects would not implement this for obvious reasons. However, it does not catch user-defined iterables that do not implement it, nor do generator expressions, which iter can deal with. However, this can be done in a line, and adding a simple or expression checking for generators would fix this problem. (Note that writing type(my_generator_expression) == generator would throw a NameError. Refer to this answer instead.)

    You can use GeneratorType from types:

    >>> import types
    >>> types.GeneratorType
    
    >>> gen = (i for i in range(10))
    >>> isinstance(gen, types.GeneratorType)
    True
    

    --- accepted answer by utdemir

    (This makes it useful for checking if you can call len on the object though.)

提交回复
热议问题