Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Several modules in a package importing one common module

Tags:

python

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?

like image 775
morpheous Avatar asked Jun 01 '10 14:06

morpheous


1 Answers

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.

like image 99
Alex Martelli Avatar answered Dec 06 '22 04:12

Alex Martelli