I am playing around with the AIMA python project, but I'm having trouble with importing the logic.py file into main.py. The following is folder structure:
project/
aima/
__init__.py
utils.py
logic.py
main.py
I added the folder to my python path variable. Every time I do
# main.py
import aima.logic as logic
I get this error:
File "main.py", line 2, in
import aima.logic as logic
File "/project/aima/logic.py", line 34, in
from utils import (
ImportError: No module named 'utils'
I thought this was strange since logic.py imports the utils file it should be fine since they are under the same directory.
I tried searching for answers, but most of them mention adding to python module search path and adding __init__.py and do not work for me.
Trying this may be good
from project.aima import logic
Related
So, I encountered a ModuleNotFoundError when trying to import a module in a subpackage that imports another subpackage under its directory (so it's a subsubpackage to the main directory). I have put empty __init__.py files under both the subdirectory and subsubdirectory. The code was run in Python 3.9.7.
Here's what the structure looks like:
|- main.py
|- subpackage/
|- __init__.py
|- submod.py
|- subsubpackage/
|- __init__.py
|_ subsubmod.py
The code
In main.py, I have:
from subpackage import submod
def main():
x = submod.test_func(3)
print(x)
if __name__ == 'main':
main()
and in submod.py, I want to import subsubmod.py under subsubpackage/, so I have:
from subsubpackage import subsubmod
def test_func(a):
return subsubmod.addone(a)
and finally, in subsubmod.py:
def addone(x):
return x+1
The error message:
Now if I run main.py, I got
Traceback (most recent call last):
File "/Users/anonymous/test/main.py", line 1, in
<module>
from subpackage import submod
File "/Users/anonymous/test/subpackage/submod.py",
line 1, in <module>
from subsubpackage import subsubmod
ModuleNotFoundError: No module named 'subsubpackage'
My question and confusion
I'm not sure what I have done wrong. I realized that submod.py can be run separately, so it seems that the issue occurs when the import goes down more than one subdirectory? I wonder if there's a way around this issue, or should I just use a different structure to organize my scripts.
Putting a dot before the package name worked for me.
from .subsubpackage import subsubmod
Looks like when you are in a package if you don't use relative import it will look for your packages somewhere else.
You can find more information here:
Python documents about import system
StackOverflow question about relative imports
This question keeps showing up on Stack Overflow and I can understand why. So today I took the time to create a nested project with 1 top module and 2 nested sub modules both with classes in them. And another class was also created in the top module folder. This is also considered a module by python. But it's in the same folder as the top module.
The skeleton nested module project is now live on Github at:
HdlHelpers Nested Modules Skeleton Project
I have the following file/folder structure:
testpackage (folder)
src (folder)
__init__.py
module1.py
tests
__init__.py
test_module1.py
just for clearance: the "module1.py" is under the "src" folder which is under the "testpakcage" folder.
"tests" is also under the "testpakcage" folder - same level as the "src" one.
module1.py has a class named "class1" as so:
class class1:
def method1 (self):
print('i am method1')
in test_module1.py I want to run tests on the above module. this is it's contents:
import unittest
from testpackage.src import module1
t = module1.class1()
t.method1()
this package is not installed, and I don't instead to install or submit it anywereh, I'm just trying to find the best structuring practice for me, for future packaging creation.
problem is: when I run the following either from the "tests" or "testpackage" folder:
/usr/bin/python3.6 -m unittest discover
I get the following error:
E
======================================================================
ERROR: test_module1 (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_module1
Traceback (most recent call last):
File "/usr/lib64/python3.6/unittest/loader.py", line 428, in _find_test_path
module = self._get_module_from_name(name)
File "/usr/lib64/python3.6/unittest/loader.py", line 369, in _get_module_from_name
__import__(name)
something similar also happens when I just try to run "test_module1.py" from the "tests" folder:
Traceback (most recent call last):
File "test_module1.py", line 5, in <module>
from testpackage.src import *
ModuleNotFoundError: No module named 'testpackage'
so I tried changing the "import" line with a few alternatives but none of them work. each one of those was a different attempt (not all of them at once):
from testpackage.src import *
import testpackage.src.module1 as module1
import ..src.module1
from ..src.module1 import class1
searching stackoverflow I found solutions that worked for some but not for those using python 3 and above - which is my case.
any suggestions? I think what I'm trying to do is rather simple and I'm missing something really basic here.
I'm using python3.6 by way
I'm wondering if you saw different errors for some of those different import attempts you made. Not sure if this will solve your problem, but this is one way it would generally be accomplished.
First, I am not sure what the top level of your package is supposed to be. Do you reference testpackage in any of the code in the src folder? If so, that top folder should also contain an __init__.py file.
Now, at the very top of your test_module1.py file, add:
import sys
pkg_dir = ".." # if "src" if the top level folder else "..." if testpackage is the top level folder
sys.path.append(pkg_dir)
Note you must change pkg_dir depending on your module's structure.(which I cannot tell from your question).
What this code does is add the folder containing the top level folder of your package to the python import search tree. This can solve problems that the relative import in your example file will not: if the files in your module use module-level imports (e.g. import testpackage.src.module2 in module1.py). This is common in packages with multiple submodules that cross-import.
I have the following set up.
~/python/pyct/lib/
├── printer.py
└── utils.py
~/apps/proj/
└── main.py
~/python/pyct/lib/utils.py
def printFunc(content):
print(content)
~/python/pyct/lib/printer.py
import utils # this breaks sometimes
# import pyct.lib.utils as utils # this works always
def printer(content):
utils.printFunc(content)
~/apps/proj/main.py
from pyct.lib.printer import printer
printer("hi")
Value of PYTHONPATH=$HOME/python
When I import printer.py in a file inside ~/python/pyct/lib/, everything runs as expected.
When I run main.py from ~/apps/proj/, I get the following error:
Traceback (most recent call last):
File "main.py", line 1, in <module>
from pyct.lib.printer import printer
File "~/python/pyct/lib/printer.py", line 1, in <module>
import utils
ModuleNotFoundError: No module named 'utils'
I have tried using relative imports but that doesn't work. I have gone through this resource but could get the scenario working.
I am aware that the problem can be solved using absolute path in imports but I want to make a dir with multiple python files which will act as a library. Then use the core component else where outside the directory.
How can I achive the above scenario working.
Any resources to understand python imports will be very helpful.
The problem here is that ~/python/pyct/lib/printer.py looks for module named utils in its working directory - not in directory where it is placed itself.
You can use relative import in ~/python/pyct/lib/printer.py:
from . import utils
python will then look for module relative to the path of the importing one instead of working directory.
Im trying to import a module from a different sub directory in Python 3 and I'm having trouble getting the script running. The current file structure I have is:
/lets_import
__init__.py
/app
__init__.py
main.py
server.py
/tests
__init__.py
tests_main.py
tests_main.py imports a function from server.py like this:
from app.server import add
(add is the function being imported from server.py)
init files are empty. They are there so that each sub dir is seen as a package.
When I run tests_main.py I get the following error
File "tests/tests_main.py", line 2, in <module>
from myapp.server import add
ImportError: No module named 'myapp'
I tried running it from the root level folder like this python test/tests_main.py but still got the same error.
Is there a way to do this without having to manipulate PYTHONPATH?
I have a main.py file in the folder project and read.py in the folder ./project/utils. In the main.py, I called
import sys, os
sys.path.append('./utils/')
from utils.read import function1
However, when I use the python main.py command, I got the error
ImportError: No module named utils.read. What should I change? Thanks all
i think you need to add __init__.py
in your directory..
make sure you have __init__.py in utils folder.. then only python will understand it is package folder contains py
__init__.py specifies that the folder is actually a package. a package in python is a directory containing .py files (modules). In every folder which is a package (that is, a folder containing multiple .py files) you should define __init__.py.
It can be empty, or you can put some statements to execute when the package is imported (or modules from the package).
For exmaple, let's take this directory tree:
/dev/package/greeter.py
and current working directory is /dev.
>>> from package import greeter
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
from package import greeter
ImportError: No module named package
import pakcage results in the same error. When adding __init__.py into the package folder, it works. My init is simple as
print 'init executed'
>>> from package import greeter
init executed
>>>
One common functionality to put in __init__.py is the __all__ variable. You can read more about it here Can someone explain __all__ in Python?