Test if a variable is a list or tuple

前端 未结 13 1416
余生分开走
余生分开走 2020-12-22 16:53

In python, what\'s the best way to test if a variable contains a list or a tuple? (ie. a collection)

Is isinstance() as evil as suggested here? http://w

13条回答
  •  半阙折子戏
    2020-12-22 17:29

    There's nothing wrong with using isinstance as long as it's not redundant. If a variable should only be a list/tuple then document the interface and just use it as such. Otherwise a check is perfectly reasonable:

    if isinstance(a, collections.Iterable):
        # use as a container
    else:
        # not a container!
    

    This type of check does have some good use-cases, such as with the standard string startswith / endswith methods (although to be accurate these are implemented in C in CPython using an explicit check to see if it's a tuple - there's more than one way to solve this problem, as mentioned in the article you link to).

    An explicit check is often better than trying to use the object as a container and handling the exception - that can cause all sorts of problems with code being run partially or unnecessarily.

提交回复
热议问题