Can't import my own modules in Python

PythonImportModulePackage

Python Problem Overview


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:

myapp/__init__.py
myapp/myapp/myapp.py
myapp/myapp/SomeObject.py
myapp/tests/TestCase.py

Now I'm trying to get something like this:

myapp.py
===================
from myapp import SomeObject
# stuff ...

TestCase.py
===================
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

Python Solutions


Solution 1 - Python

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

import SomeObject

since it is in the same folder. For TestCase.py, 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 TestCase.py, you would have to mess with your path. This can be done within Python:

import sys
sys.path.append("..")
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 setup.py 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.

Solution 2 - Python

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/"

Solution 3 - Python

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

/Library/Python/2.7/site-packages

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

/opt/awesome/custom_python_modules

Solution 4 - Python

You can try

from myapp.myapp import SomeObject

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

Solution 5 - Python

You need to have

__init__.py

in all the folders that have code you need to interact with. You also need to specify the top folder name of your project in every import even if the file you tried to import is at the same level.

Solution 6 - Python

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

from setuptools import setup
setup(name='myapp')

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

Solution 7 - Python

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.
e.g.
python -m pip install <package-name>
instead of
pip install <package-name>

Solution 8 - Python

In my case it was Windows vs Python surprise, despite Windows filenames are not case sensitive, Python import is. So if you have Stuff.py file you need to import this name as-is.

Solution 9 - Python

let's say i write a module

import os
my_home_dir=os.environ['HOME'] // in windows 'HOMEPATH'
file_abs_path=os.path.join(my_home_dir,"my_module.py")

with open(file_abs_path,"w") as f:
   f.write("print('I am loaded successfully')")

import importlib
importlib.util.find_spec('my_module') ==> cannot find

we have to tell python where to look for the module. we have to add our path to the sys.path

 import sys
 sys.path.append(file_abs_path)

now importlib.util.find_spec('my_module') returns:

  ModuleSpec(name='my_module', loader=<_frozen_importlib_external.SourceFileLoader object at 0x7fa40143e8e0>, origin='/Users/name/my_module.py')

we created our module, we informed python its path, now we should be able to import it

 import my_module

//I am loaded successfully

Solution 10 - Python

Short Answer:

python -m ParentPackage.Submodule

Executing the required file via module flag worked for me. Lets say we got a typical directory structure as below:

my_project:
 | Core
    ->myScript.py
 | Utils
   ->helpers.py
 configs.py

Now if you want to run a file inside a directory, that has imports from other modules, all you need to do is like below:

python -m Core.myscript

PS: You gotta use dot notation to refer the submodules(Files/scripts you want to execute). Also I used python3.9+. So I didnt require neither any init.py nor any sys path append statements.

Hope that helps! Happy Coding!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser623990View Question on Stackoverflow
Solution 1 - PythonDavid RobinsonView Answer on Stackoverflow
Solution 2 - PythonZenonView Answer on Stackoverflow
Solution 3 - PythonjmontrossView Answer on Stackoverflow
Solution 4 - Python阿东刘View Answer on Stackoverflow
Solution 5 - PythonKrysaleadView Answer on Stackoverflow
Solution 6 - Python未来陆家嘴顶尖的投资人View Answer on Stackoverflow
Solution 7 - PythonsziraquiView Answer on Stackoverflow
Solution 8 - PythonastrowalkerView Answer on Stackoverflow
Solution 9 - PythonYilmazView Answer on Stackoverflow
Solution 10 - PythonDeekshith AnandView Answer on Stackoverflow