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
 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值