2012-10-29 32 views
0

我正在嘗試使用一個名爲interface.py的模塊,它定義了一個條件列表和一些函數來檢查這些條件的參數。然而,有成千上萬的條件,所以我想使用字典而不是列表來防止需要查看所有這些條件。要做到這一點,我用下面的代碼:儘快在Python模塊中執行代碼

def listToDictionary(list): 
    """This function takes a list of conditions and converts it to a dictionary 
    that uses the name of the condition as a key.""" 

    d = {} 
    for condition in list: 
     if condition.name.lower() not in d: 
      d[condition.name.lower()] = [] 
     d[condition.name.lower()].append(condition) 
    return d 

conditionList = listToDictionary(conditions.list) #the condition list comes from another module 

接着,在該文件是帶參數的使用條件列表比較實際的接口功能 - 這些功能都寫假設conditionList將是一本字典。

不幸的是,這是行不通的。提供錯誤細節是很困難的,因爲這個代碼是由一個Django頁面導入的,我試圖避免談論Django,所以這個問題並不複雜。基本上包含這些代碼的頁面將不會加載,如果我將其更改回僅使用列表,一切正常。

我懷疑這個問題與Python如何對待導入語句有關。我需要listToDictionary轉換在導入interface.py後立即運行,否則接口函數將會期待一個字典並獲取一個列表。有什麼方法可以確保這種情況發生?

+0

Python在導入時執行模塊的主體,所以這不是你的問題。 –

+6

命名一個變量'list'絕不是一個好主意,你會隱藏內置類型。改爲使用其他名稱。 –

+1

@MartijnPieters我甚至會說:命名變量'list'總是一個可怕的想法 –

回答

1

一個受過教育的猜測:conditions.list中的列表在導入模塊時尚未完全構建。因此,您會收到一本缺少一些條目或甚至空的字典,這會在稍後導致問題。儘量推遲字典的建設,像這樣:

conditionTable = None  # shouldn't call it list if it's a dict 

def get_cond_table(): 
    global conditionTable 
    if conditionTable is None: 
     conditionTable = listToDictionary(conditions.list) 
    return conditionTable 

而是在功能指的是conditionList的,請參閱get_cond_table()

+0

感謝您的建議 - 不幸的是我仍然遇到同樣的問題。我開始認爲這個問題可能出現在Django端,在這種情況下,試圖簡化問題可能會讓我自己陷入困境。 – Keilan

1

好吧,我發現問題出在另一個函數上,它仍然期待字典是一個列表。我不能馬上看到它的原因是Django留下了一個非常神祕的錯誤信息。我能夠使用python manage.py shell和手動導入模塊獲得更好的一個。

感謝您的幫助。