2010-12-01 151 views
0

所以我有一個很大的項目,裏面有很多模塊,我想運行一些分析。我有一個配置文件模塊,基本上只是提供了一個裝飾器,我可以添加到一個函數來調用它時調用它。python模塊導入問題

問題是,我必須將該模塊導入到我擁有的幾十個模塊中。這很好,我猜想,但我不能推動與導入分析模塊或函數的裝飾器的代碼到版本控制。這意味着每次我導入/導出時,我都必須添加/刪除所有我的分析代碼。

是否有任何類型的系統來管理此添加/刪除分析代碼,而無需在我的項目的每個模塊中手動導入/刪除模塊?我們使用mercurial,但我不能真正搞亂mercurial設置或建立分支。

回答

2

你可以創建你的分析模塊,使得它導入你的其它模塊和詮釋自己的職能:

# these are the modules you want to profile 
import foo 
import huh 

# This is a profiling function 
# yours would do something smarter 
def profile(f): 
    def gotcha(*args, **kwds): 
     print "before" 
     result = f(*args, **kwds) 
     print "after" 
     return result 
    return gotcha 

# these are the functions in those modules that you 
# want to profile. Each one is patched here instead 
# of decorated there. 
foo.bar = profile(foo.bar) 
huh.baz = profile(huh.baz) 
huh.hmm = profile(huh.hmm) 

這樣你就不必修改這些模塊,但如果您選擇導入這個分析模塊在運行時的任何地方,它會「修補」所有其他模塊,如你所願

你應該能夠類似地修飾類方法。

+0

哇,這真是個好主意。我絕對認爲我會試試這個 – Falmarri 2010-12-01 20:53:35

0

爲什麼不只是創建一個包含所有分析更改的分支,然後在想要測試時合併分支......並在之後恢復所有分支。

git使它變得更容易,它的「git stash」,但使用分支不應該更難。

+0

我想到了這一點。但也許是因爲我有一種傾向,當我做任何事情時都會拋棄mercurial repo而不是推拉,我厭倦這樣做> _ < – Falmarri 2010-12-01 20:32:07