문제

Is there a good one-stop-shop Python reference for choosing attributes to use with hasattr() to identify types.

For example, the following is for a sequence which is not a string:

def is_sequence(arg):
    return (not hasattr(arg, "strip") and
            hasattr(arg, "__getitem__") or
            hasattr(arg, "__iter__")) 

It would be nice to have a solid reference for choosing the best patterns quickly.

도움이 되었습니까?

해결책

Use the virtual subclasses that have already been written for you in the collections module (collections.abc in Python 3.3).

To check if something is a non-string sequence, use

from collections import Sequence    # collections.abc in Python 3.3
isinstance(arg, Sequence) and not isinstance(arg, basestring)    # str in Python 3

다른 팁

Use the appropriate abstract base class:

import collections
isinstance([], collections.Sequence) # ==> true
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top