Can't import my own modules in Python


I'm having a hard time understanding how module importing works in Python (I've never done it in any other language before either).

Let's say I have:


Now I'm trying to get something like this:
from myapp import SomeObject
# stuff ...
from myapp import SomeObject
# some tests on SomeObject

However, I'm definitely doing something wrong as Python can't see that myapp is a module:

ImportError: No module named myapp
2/21/2012 6:39:15 PM

Accepted Answer

In your particular case it looks like you're trying to import SomeObject from the and scripts. From, do

import SomeObject

since it is in the same folder. For, do

from ..myapp import SomeObject

However, this will work only if you are importing TestCase from the package. If you want to directly run python, you would have to mess with your path. This can be done within Python:

import sys
from myapp import SomeObject

though that is generally not recommended.

In general, if you want other people to use your Python package, you should use distutils to create a setup script. That way, anyone can install your package easily using a command like python install and it will be available everywhere on their machine. If you're serious about the package, you could even add it to the Python Package Index, PyPI.

2/21/2012 6:46:03 PM

The function import looks for files into your PYTHONPATH env. variable and your local directory. So you can either put all your files in the same directory, or export the path typing into a terminal::

export PYTHONPATH="$PYTHONPATH:/path_to_myapp/myapp/myapp/"

exporting path is a good way. Another way is to add a .pth to your site-packages location. On my mac my python keeps site-packages in /Library/Python shown below


I created a file called awesome.pth at /Library/Python/2.7/site-packages/awesome.pth and in the file put the following path that references my awesome modules


You can try

from myapp.myapp import SomeObject

because your project name is the same as the which makes it search the project document first


In your first myapp directory ,u can add a file and add two python code in

from setuptools import setup

in your first myapp directory in commandline , use pip install -e . to install the package

pip install on Windows 10 defaults to installing in 'Program Files/PythonXX/Lib/site-packages' which is a directory that requires administrative privileges. So I fixed my issue by running pip install as Administrator (you have to open command prompt as administrator even if you are logged in with an admin account). Also, it is safer to call pip from python.
python -m pip install <package-name>
instead of
pip install <package-name>


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]