Type checking: an iterable type that is not a string

后端 未结 2 400
庸人自扰
庸人自扰 2020-12-16 14:08

To explain better, consider this simple type checker function:

from collections import Iterable
def typecheck(obj):
    return not isinstance(obj, str) and i         


        
相关标签:
2条回答
  • 2020-12-16 14:21

    In python 2.x, Checking for the __iter__ attribute was helpful (though not always wise), because iterables should have this attribute, but strings did not.

    def typecheck(obj): return hasattr(myObj, '__iter__')
    

    The down side was that __iter__ was not a truely Pythonic way to do it: Some objects might implement __getitem__ but not __iter__ for instance.

    In Python 3.x, strings got the __iter__ attribute, breaking this method.

    The method you listed is the most efficient truely Pythonic way I know in Python 3.x:

    def typecheck(obj): return not isinstance(obj, str) and isinstance(obj, Iterable)
    

    There is a much faster (more efficient) way, which is to check __iter__ like in Python 2.x, and then subsequently check str.

    def typecheck(obj): return hasattr(obj, '__iter__') and not isinstance(obj, str)
    

    This has the same caveat as in Python 2.x, but is much faster.

    0 讨论(0)
  • 2020-12-16 14:30

    I check it with this code and it work fine with Python 2 and 3

    from __future__ import unicode_literals
    import types
    import collections
    
    var = ["a", "b", "c"]
    if isinstance(var, collections.Iterable) and \
            not isinstance(var, types.StringTypes):
        return var
    
    0 讨论(0)
提交回复
热议问题