Python Type Comparison

This article 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 following 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 all type comparisons. They're very, very rarely necessary. Sometimes, they help to check parameter types in a function -- even that's rare. Wrong type data will raise an exception, and that's all you'll ever need.
 

 

 

However, if the type comparison is what you really wants, (they must be some case when it is needed), you can do as above.

 

I am attaching 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
 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(Python Type Comparison)