开发者

Several modules in a package importing one common module

I am writing a python package. I am using the concept of plugins - where each plugin is a specialization of a Worker class. Each plugin is written as a module (script?) and spawned in a sep开发者_StackOverflow社区arate process.

Because of the base commonality between the plugins (e.g. all extend a base class 'Worker'), The plugin module generally looks like this:

import commonfuncs

def do_work(data):
    # do customised work for the plugin
    print 'child1 does work with %s' % data

In C/C++, we have include guards, which prevent a header from being included more than once.

Do I need something like that in Python, and if yes, how may I make sure that commonfuncs is not 'included' more than once?


No worry: only the first import of a module in the course of a program's execution causes it to be loaded. Every further import after that first one just fetches the module object from a "cache" dictionary (sys.modules, indexed by module name strings) and therefore it's both very fast and bereft of side effects. Therefore, no guard is necessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜