0

So I have thought about it this way for a Python 2.7 project. It would be composed of two independent parts requiring a common class (module) file in a third package:

SomeRootFolder/Package1Folder/manyPythonModuleFiles.py
SomeRootFolder/Package2Folder/manyPythonModuleFiles.py
SomeRootFolder/SharedPackageFolder/OneCommonClassNeedsToBeShared.py

What I want to do is to import the common class in the shared package from both packages. The two first packages do not require to interact together but needs that one class. The python programs might be runned with the console opened from within the two package folders themselves, such as:

cd Package1Folder
python SomeMainFile.py

If it is easier, the Python call could be like python Package1Folder/SomeMainFile.py but I need to plan this.

Could you provide how I could do the relative imports from package 1 or 2 for a file in the third shared package? Do I need an __init__.py file in the SomeRootFolder folder? I am always confused by relative imports and those import standards and syntax that are different between Python 2 and 3. Also could you validate to me that this is an acceptable way to proceed? Any other ideas?

Thanks all!

Guillaume Chevalier
  • 9,613
  • 8
  • 51
  • 79

1 Answers1

2

If you want to use relative imports,you need __init__.py in SharedPackageFolder folder,and you can use this to import OneCommonClassNeedsToBeShared.py:

from ..SharedPackageFolder import OneCommonClassNeedsToBeShared

See more details about Rationale for Relative Imports .

With the shift to absolute imports, the question arose whether relative imports should be allowed at all. Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages. In addition, a module inside a package can't easily import itself without relative imports.

Also you can use absolute imports,relative imports are no longer strongly discouraged,using absolute_import is strongly suggested in some case.

You need to make sure SomeRootFolder is in your PYTHONPATH,or make this folder as sources root,it's more easier for you to import package or scripts in your large project,but sometimes you should be careful with absolute imports.

from SharedPackageFolder import OneCommonClassNeedsToBeShared.py

Absolute imports. From PEP 8:

Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 [7] is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.

By the way,relative imports in Python 3 might return SystemError,have a look at Question:Relative imports in Python 3. @vaultah offers some solutions,they might be helpful.

Hope this helps.

Community
  • 1
  • 1
McGrady
  • 10,869
  • 13
  • 47
  • 69