tags:

views:

48

answers:

1

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?

+3  A: 

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.

Alex Martelli
@alex: Phew!thats a relief to know. +1 for the concise (and speedy reply). Any chance on sending a link on where I may read this?
morpheous
+1: "no guard is necessary" could perhaps be stated "guards are built-in".
S.Lott
http://docs.python.org/reference/simple_stmts.html#grammar-token-import_stmt
S.Lott
@morph, I recommend the Python Tutorial, e.g. http://docs.python.org/tutorial/modules.html#more-on-modules , for starters; and Python in a Nutshell chapter 7, e.g. http://books.google.com/books?id=vpTAq4dnmuAC-).
Alex Martelli