2014-02-25 29 views
-1

我有一种情况,模块需要做一些简单但稍微耗时的初始化。最终条件之一是一对将通过初始化填写的列表;有什么令我烦恼的是,列表的作用(它们基本上是常量)与实际初始化列表之间有冲突。用Python初始化模块级列表的最简单的方法

我感到不安写这样的代码:

CONSTANT_LIST = [] 
DIFFERENT_LIST = [] 

for item in get_some_data_slowly(): 
     if meets_criteria_one(item): 
     CONSTANT_LIST.append(item) 
     continue 
     if meets_criteria_two(item): 
     DIFFERENT_LIST.append(item) 

由于普通读者会看到通常由常数占据的位置的列表,并可以期待他们为空。

OTOH,我会用相同的下引擎罩事实确定,如果我可以这样写列表理解:

CONSTANT_LIST = [i for i in some_data() if criterion(i)] 

等等......除了我需要绘制两个列表来自相同的(稍微耗时的)源,所以两个列表解析会使代码明显变慢。

更糟糕的是,应用程序是这样的,躲在后面的常量方法:

__private_const_list = None 
__other_private_list = None 

def public_constant_list(): 
    if __private_const_list: return __private_const_list 
    # or do the slow thing now and fill out both lists... 
    # etc 

def public_other_const_list(): 
    # same thing 

是因为可能使用频率那种愚蠢的基本上是1元会话。

正如你可以看到它不是一个火箭科学问题,但我的Python感觉并没有刺痛。这里有什么合适的pythonic模式?

回答

1

循环非常清晰。不要太巧妙地混淆它。只需使用意见,以帮助解释

CONSTANT_LIST = [] # Put a comment here to tell the reader that these 
DIFFERENT_LIST = [] # are constants that are filled in elsewhere 
""" 
Here is an example of what CONSTANT_LIST looks like 
... 
Here is an example of what DIFFERENT_LIST looks like 
... 
""" 


for item in get_some_data_slowly(): 
    if meets_criteria_one(item): 
     CONSTANT_LIST.append(item) 
    elif meets_criteria_two(item): 
     DIFFERENT_LIST.append(item) 

也许使用elif代替continue/if

+0

集over_think = 0 – theodox