morpheous
morpheous

Reputation: 16926

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 separate 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?

Upvotes: 12

Views: 4420

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 881477

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.

Upvotes: 27

Related Questions