Python模块导入问题

0 投票
2 回答
759 浏览
提问于 2025-04-16 07:54

我有一个大项目,里面有很多模块,我想对它进行一些性能分析。我有一个性能分析模块,基本上就是提供一个装饰器,我可以把它加到一个函数上,这样在调用这个函数的时候就能进行性能分析。

问题是,我得把这个模块导入到我所有的模块里,大概有几十个。这倒也没什么,但我不能把带有性能分析模块导入的代码或者加了装饰器的函数推送到版本控制系统里。这就意味着每次我导入或导出代码时,都得手动添加或删除所有的性能分析代码。

有没有什么办法可以管理这个性能分析代码的添加和删除,而不需要在我项目的每个模块里手动导入或删除模块?我们用的是mercurial,但我不太能改动mercurial的设置或者创建分支。

2 个回答

0

为什么不直接创建一个包含所有性能分析更改的分支,然后在想测试的时候合并这个分支,测试完后再撤销所有更改呢?

使用git的话,这样做会简单一些,因为它有个“git stash”的功能,但其实使用分支也不应该太难。

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)

这样你就不需要去修改那些模块了。如果你在运行时选择导入这个性能分析模块,它会像你想的那样“修补”所有其他模块。

你也可以用类似的方法给类的方法加上装饰。

撰写回答