views:

101

answers:

2

I want to have a number of files imported in a general python file and then include that file when I need the imported modules in the current module. This of course will lead to errors and re-imports if using the from x import y, however when using the "normal" import statement I end up with long instruction statements, for example:

x = importModule.directoryName1.directoryName2.moduleName.ClassName()

whereas I'd like to do the following:

x = importModule.ClassName()

but as I said before, doing this:

from importModule.directoryName1.directoryName2.moduleNam import ClassName

in a general file doesn't work since I include importModule in ClassName.

So, I'm basically wondering if there's anyway around this (something like an using statement, such as the one in C++, perhaps?)

+2  A: 

Well, you could do

from importModule.directoryName1.directoryName2 import moduleName as importModule

but that's kind of ugly and very confusing, and won't score you a lot of points with the Python programmers who read your code later.

mipadi
Doesn't work if you want to import from `moduleName` and `module2Name` in the same file.
Chris B.
Why wouldn't you just do `import importModule.directoryName1.directoryName2.moduleName as importModule`?
Mike DeSimone
+3  A: 

It sounds like you've got recursive imports (importModule refers to moduleName, and moduleName refers to importModule. If you refactor, you should be able to use

from importModule.directoryName1.directoryName2.moduleName import ClassName

To refactor, you can change the order in which things are imported in moduleName so that the class definition of ClassName occurs before the importModule import; as long as each file defines the references needed by the other module before they try and import the other module, things will work out.

Another way to refactor: you could always import ClassName within the function where it's used; as long as the function isn't called before moduleName is imported, you'll be fine.

The best way to refactor, though, is to move some classes or references into their own module, so you don't have any situation where A imports B and B imports A. That will fix your problem, as well as make it easier to maintain things going forward.

Chris B.
+1 paragraph that begins "The best way".
msw