I'm trying to re-organize my Python project by moving scripts from the package directory into a top level script directory. After these changes, this is what my project hierarchy looks like:
MyProject/
setup.py
scripts/
my_package.py
my_package/
__init__.py
module_foo.py
Notice how the script and the package have the same name.
The script my_package.py
looks something like this:
# MyProject/scripts/my_package.py
import os
try:
import my_package
print os.path.abspath(my_package.__file__)
except ImportError as e:
print e
When we run the above script the interpreter imports the current module rather than the package of the same name (note: the package my_package
has already been installed into site-packages
as an egg and our virtual environment is properly activated.)
How can I import the package my_package
from the script my_package.py
given they have the same name?
What happens if a module is imported twice? The module is only loaded the first time the import statement is executed and there is no performance loss by importing it again. You can examine sys. modules to find out which modules have already been loaded.
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory. As sys.
The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.
For me it works with
sys.path.insert(0, '..')
since the import does something like for path in sys.path:
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With