Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a Python package from a script with the same name

Tags:

python

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?

Other Technical Info:

  • Python 2.7.3
  • Ubuntu Server 12.04 LTS
  • VirtualEnv 1.11.6
like image 987
AlfaZulu Avatar asked Jun 29 '14 15:06

AlfaZulu


People also ask

What happens if I import the same module twice Python?

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.

How do I import another Python package?

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.

What does adding __ init __ py do?

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.


1 Answers

For me it works with

sys.path.insert(0, '..')

since the import does something like for path in sys.path:.

like image 142
User Avatar answered Oct 02 '22 14:10

User