开发者

import statement mess in python

I want to have a number of files imported in a general python fi开发者_C百科le 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?)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜