我正在嘗試使用一個名爲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後立即運行,否則接口函數將會期待一個字典並獲取一個列表。有什麼方法可以確保這種情況發生?
Python在導入時執行模塊的主體,所以這不是你的問題。 –
命名一個變量'list'絕不是一個好主意,你會隱藏內置類型。改爲使用其他名稱。 –
@MartijnPieters我甚至會說:命名變量'list'總是一個可怕的想法 –