Python Type Compparison

2948 ワード

This artic is based on the discussion in this page:  http://stackoverflow.com/questions/707674/how-to-compare-type-of-an-object-in-python
 
 
From this page,it has the follwing code sample.
 
 
# check if x is a regular string
type(x) == str
# check if x is either a regular string or a unicode string
type(x) in [str, unicode]
# alternatively:
isinstance(x, basestring)
# check if x is an integer
type(x) == int
# check if x is a NoneType
x is None
 
 
Also,the author commented that
 
 
 
S.Lottは書いています
First,avoid a ll type comprisos.The're very,very rarely necessary.Sometimes,they help to check parameter type s in a function--even that's rare.Wrong type data will rase exception,and that's.exception。
 
 
 
However,if the type comprison is what you really wants,(they must be some case when it is needed),you can do as above.
 
I am ataching the example that I am having for check the type of parameter to a certain function.
 
def check(n, p, a=None):
    """
    :param n: the # of instance to start
    :param p: the path to the Command/Script to start
    :param a: this is optional argument,
    """

    assert(n is not None and n > 0)
    assert(p is not None and p != "")
    assert(a is None or a != "")
    
    
    if (not isinstance(n, int)): raise TypeError("Argument 'n' expect integer")
    if (n is None or n <= 0): raise ValueError("Argument 'n' invalid");
    if (a is not None):
        if (type(a) != StringType): raise TypeError("Argument 'a': expect string")
        if (type(a) is not StringType): raise TypeError("Argument 'a': expect string")
        if (type(a) != str): raise TypeError("Argument 'a': expect string")
        if (type(a) is not str): raise TypeError("Argument 'a': expect string")
        # while this is wrong, because is is like identity equal operator
        # it is like 
        #     a is b
        #  is equivalent
        #     id(a) == id(b)
        # 
        # if (a is not str): raise TypeError("Argument 'a': expect string")
        if (not isinstance(a, str)): raise TypeError("Argument 'a': expect string")
        if (not (type(a) in [str, unicode])): raise TypeError("Argument 'a': expect string")
    
    pass