python 用list,dic實現switch功能的一個奇葩現象

def daemonLog(moduleDiscription = "test123", logPath='/root/Desktop/dns/test.log', logLevel=4):
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                        datefmt='%m-%d %H:%M',
                        filename=logPath,
                        filemode='a+')
    thisLog = logging.getLogger(moduleDiscription)
    logLevelDict = {
        'debug': thisLog.debug('a'),
        'info': thisLog.info('b'),
        'warning': thisLog.warning('c'),
        'error': thisLog.error('d')
    }
    print logLevelDict.get('info')
    

今天實現日誌相關功能的實現的時候發現了一些比較奇葩的問題

毫無疑問用dic,和list可以實現switch的作用,而且簡潔易讀,但今天想用dic實現一個logging模塊的不同級別的日誌類型,但是發現無論是用dic還是list都會導致dic和list的所有級別的日誌類型都會輸出到日誌文件中去

1、

# logLevelList = [thisLog.debug('a'),thisLog.info('b'),thisLog.warning('c'),thisLog.error('d')]

# print logLevelList[ 0 ]

2、

    logLevelDict = {
        'debug': thisLog.debug('a'),
        'info': thisLog.info('b'),
        'warning': thisLog.warning('c'),
        'error': thisLog.error('d')
    }
    print logLevelDict.get('info')

1,2效果一樣,已醉,目前猜測可能是在遍歷的時候,list和dic中的表達式都被執行了一遍,而且由於該方式不返回值,所以取出的值爲None,目測如此,所以可以採用用lambda函數的方式,這樣就可以保證在遍歷的時候只是取出對應的函數而不是直接執行了對應的函數,實現如下,可以達到預期效果

# coding=utf-8
import logging

def daemonLog(moduleDiscription = "test123", logPath='/root/Desktop/dns/test.log', logLevel=4):
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                        datefmt='%m-%d %H:%M',
                        filename=logPath,
                        filemode='a+')
    thisLog = logging.getLogger(moduleDiscription)
    logLevelDict = {
        'debug': lambda: thisLog.debug('a'),
        'info': lambda: thisLog.info('b'),
        'warning': lambda: thisLog.warning('c'),
        'error': lambda: thisLog.error('d')
    }
    logLevelDict.get('info')()




    # thisLog.debug('z')
    # thisLog.info('bb')
    # thisLog.warning('c')
    # thisLog.error('dddd')


daemonLog()

有種簡約不簡單的感覺,注意logLevelDict.get('info')()這裏如果沒有最後的括號你只是取出了一個函數而已,加上括號(如果你有設參數,這裏需要填入參數)才表示執行了該函數


發佈了11 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章