Alex Rivera | Logout

Properly importing modules in Python

Asked 2009-05-22T02:09:07.290
11

How do I set up module imports so that each module can access the objects of all the others?

I have a medium size Python application with modules files in various subdirectories. I have created modules that append these subdirectories to sys.path and imports a group of modules, using import thisModule as tm. Module objects are referred to with that qualification. I then import that module into the others with from moduleImports import *. The code is sloppy right now and has several of these things, which are often duplicative.

First, the application is failing because some module references aren't assigned. This same code does run when unit tested.

Second, I'm worried that I'm causing a problem with recursive module imports. Importing moduleImports imports thisModule, which imports moduleImports . . . .

What is the right way to do this?

Edit
Report

1 Answer

4

The way to do this is to avoid magic. In other words, if your module requires something from another module, it should import it explicitly. You shouldn't rely on things being imported automatically.

As the Zen of Python (import this) has it, explicit is better than implicit.

answered 2009-05-22T09:10:17.553

Your Answer