Python中實(shí)現(xiàn)參數(shù)類型檢查的簡(jiǎn)單方法

字號(hào):


    這篇文章主要介紹了Python中實(shí)現(xiàn)參數(shù)類型檢查的簡(jiǎn)單方法,本文講解使用裝飾器實(shí)現(xiàn)參數(shù)類型檢查并給出代碼實(shí)例,需要的朋友可以參考下
    Python是一門弱類型語言,很多從C/C++轉(zhuǎn)過來的朋友起初不是很適應(yīng)。比如,在聲明一個(gè)函數(shù)時(shí),不能指定參數(shù)的類型。用C做類比,那就是所有參數(shù)都是void*類型!void類型強(qiáng)制轉(zhuǎn)換在C++中被廣泛地認(rèn)為是個(gè)壞習(xí)慣,不到萬不得已是不會(huì)使用的。
    Python自然沒有類型強(qiáng)制轉(zhuǎn)換一說了,因?yàn)樗莿?dòng)態(tài)語言。首先,所有對(duì)象都從Object繼承而來,其次,它有強(qiáng)大的內(nèi)省,如果調(diào)用某個(gè)不存在的方法會(huì)有異常拋出。大多數(shù)情況,我們都不需要做參數(shù)類型栓查,除了一些特殊情況。例如,某個(gè)函數(shù)接受一個(gè)str類型,結(jié)果在實(shí)際調(diào)用時(shí)傳入的是unicode,測(cè)試過程中又沒有代碼覆蓋到,這樣問題就比較嚴(yán)重了。解決方法也很簡(jiǎn)單,借助Python的內(nèi)省,很容易就能判斷出參數(shù)的類型。但是每個(gè)地方都寫檢查代碼會(huì)很累贅,何況它帶來的實(shí)際價(jià)值并不高。一個(gè)好的解決方法是使用裝飾器。
    '''
    >>> NONE, MEDIUM, STRONG = 0, 1, 2
    >>>
    >>> @accepts(int, int, int)
    ... def average(x, y, z):
    ... return (x + y + z) / 2
    ...
    >>> average(5.5, 10, 15.0)
    TypeWarning: 'average' method accepts (int, int, int), but was given
    (float, int, float)
    15.25
    '''
    def accepts(*types, **kw):
    """ Function decorator. Checks that inputs given to decorated function
    are of the expected type.
    Parameters:
    types -- The expected types of the inputs to the decorated function.
    Must specify type for each parameter.
    kw -- Optional specification of 'debug' level (this is the only valid
    keyword argument, no other should be given).
    debug = ( 0 | 1 | 2 )
    """
    if not kw:
    # default level: MEDIUM
    debug = 1
    else:
    debug = kw['debug']
    try:
    def decorator(f):
    def newf(*args):
    if debug == 0:
    return f(*args)
    assert len(args) == len(types)
    argtypes = tuple(map(type, args))
    if argtypes != types:
    msg = info(f.__name__, types, argtypes, 0)
    if debug == 1:
    print >> sys.stderr, 'TypeWarning: ', msg
    elif debug == 2:
    raise TypeError, msg
    return f(*args)
    newf.__name__ = f.__name__
    return newf
    return decorator
    except KeyError, key:
    raise KeyError, key + "is not a valid keyword argument"
    except TypeError, msg:
    raise TypeError, msg
    def info(fname, expected, actual, flag):
    """ Convenience function returns nicely formatted error/warning msg. """
    format = lambda types: ', '.join([str(t).split("'")[1] for t in types])
    expected, actual = format(expected), format(actual)
    msg = "'%s' method " % fname \
    + ("accepts", "returns")[flag] + " (%s), but " % expected\
    + ("was given", "result is")[flag] + " (%s)" % actual
    return msg
    本質(zhì)上講,這也是一種運(yùn)行時(shí)檢查,但效果已經(jīng)不錯(cuò)了。