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?)
It sounds like you’ve got recursive imports (
importModulerefers tomoduleName, andmoduleNamerefers toimportModule. If you refactor, you should be able to useTo refactor, you can change the order in which things are imported in
moduleNameso that the class definition ofClassNameoccurs before theimportModuleimport; 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
ClassNamewithin the function where it’s used; as long as the function isn’t called beforemoduleNameis 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
AimportsBandBimportsA. That will fix your problem, as well as make it easier to maintain things going forward.