There are 10+ SO posts about this already, none of the answers works for me and I still haven't seen an example of someone importing something from a sibling directory.
src
__init__.py
test.py
package1
__init__.py
module1.py
package2
__init__.py
module2.py
(_init_.py should not be necessary on python versions greater than 3.3 but I still have them there as they make no difference)
in test.py I have
import package1.module2
and it works fine however the problem is when I want to import something from package2 to package1, and vice versa. I have tried different import methods in module2.py and I receive these different error messages:
import src.package1.module1.py
with the error:
ModuleNotFoundError: No module named 'src'
and
from .. import package1
with the error:
ImportError: attempted relative import with no known parent package
The top answer here: How do I import a Python script from a sibling directory? also give me the exact error message as I showed above.
The answers here: How to import a Python module from a sibling folder? changes nothing.
Am I missing something or should it not be possible to import stuff between different folders/packages? Do I need the "sys.path hack"?
I gave almost all of the solutions given for similar questions a try, but none of them worked for me!
However, after banging my head to the wall, I found out that this solution does work by just removing one dot:
import sys
sys.path.append('..')
Just remove one dot from string within append method, i.e.:
sys.path.append('.')
or your can use:
sys.path.insert(0, '.')
Then you can import any module from a sibling folder.
I tried this using python 3.9.13 and it worked well.
I just spent several hours struggling with this same problem, trying various solutions from answers to the linked questions, and none of them worked. It was only when I cleared out the cruft from my various failed attempts and tried the stupidly simple solution from package1 import module1 (NB no dots, i.e. not a relative import) that it worked!
Note that your IDE may complain about this (PyCharm does in my current main project, but doesn't in a dummy project I created to test this solution separately). Nonetheless, when you run the code it should work (tested with Python 3.10 on Windows 11).
Related
My Directory is structured as follows:
superParent
│ app.py
├───custom_package
file1.py
file2.py
file3.py
file4.py
__init__.py
I am running app.py
I want to import functions from file1.py and file2.py into app.py. I also import functions from file3.py and file4.py in file1.py and file2.py.
Now when I include
from custom_package.file1 import func_abc
in app.py it throws an ModuleNotFound error. However,
from custom_package import file1
func_abc = file1.func_abc
works perfectly.
Similarly, when I am trying to import a function from file3.py into file1.py using:
from file3 import func_efg
in file1.py it throws an ModuleNotFound error. However,
from custom_package import file3
func_efg = file3.func_efg
works perfectly in file.py.
I have found a lot of similar questions in StackOverFlow, however, none of them addressed this peculiar (for me - not for everyone) behaviour. A lot of them suggest making changes to the PYTHONPATH or sys.append('path\to\custom_package') (while strongly arguing that we should not resort to this). How do we solve these import-related issues to import particular functions from custom-defined local packages from a relative directory (preferably without messing with sys.path at all)?
Additional Context (not sure if this is necessary):
I will be containerizing this and deploying the container to AKS.
Some additional StackOverflow questions which have addressed similar issues:
Can't import my own modules in Python
Importing files from different folder
ImportError: No module named <something>
Importing files from different folder
Importing modules from parent folder
How to do relative imports in Python?
relative import in Python 3
I would suggest to use the leading dot format for package relative imports
And also to add your submodules (file1, file2, etc) to custom_package/__init__.py as it is showed here: submodules
I have searched this question over stackoverflow but can't find an answer that fixes this. I am trying to learn how to do proper imports with python.
I am using Python 3.8.2 and I have the following simple directory setup.
main_folder\
folder1\
myclass.py
folder2\
testclass2.py
testclass1.py
Both testclass1.py and testclass2.py have this inside:
from folder1.myclass import Myclass
This works fine for testclass1.py, but when I run in testclass2.py it gives me an error.
ModuleNotFoundError: No module named 'folder1'
Even though I had read Python no longer requires this, I inserted an __init__.py file into folder1. This generated the same error. I then tried following directions for the init file in this article but there was no improvement. I also tried using relative paths versus absolute paths for import, but no success.
Help is much appreciated.
From testclass2.py the import should be like this:
from ..folder1.myclass import Myclass
I know a lot of questions have been posted about the intra-package importing. I want to know whether the below is the way for Python 2.7 too.
Source/
anomalyCheck/
__init__.py
DLthput.py
ULPowerStats.py
ULThput.py
config/
__init__.py
configure.py
parserTools/
__init__.py
logParser.py
utilities/
__init__.py
plotLogResults.py
__init__.py
lteDebugger.py
---- lteDebugger.py----
import parserTools.logParser
import anomalyCheck.DLthput
import utilities.plotLogResults
import configuration.TDDFDDconfiguration
import anomalyCheck.ULthput
### Work done after here ####
------DLThput.py------
from ..utilities.plotLogResults import *
from ..parserTools.logParser import *
### Work done after here ####
------ULThput.py-------
from ..parserTools.logParser import *
from ..utilities.plotLogResults import *
Error :
Upon running the lteDebugger.py file, the error is
ValueError: Attempted relative import beyond toplevel package
File "C:\Users\manojtut\Desktop\Project_LTE_SVN\Source\lteDebugger.py", line 2, in
import anomalyChecker.DLthput
File "C:\Users\manojtut\Desktop\Project_LTE_SVN\Source\anomalyChecker\DLthput.py", line 1, in
I've read almost all available docs and Guido's guide for intra-package importing. Also, I guess I've everything exactly in the right place. Am I missing something here? Please point out. Thanks a lot in advance. :) :)
Edit 1: The Problem mentioned is solved by Amber's answer. So, lteDebugger.py is working fine by importing all other modules. Now, another problem is that, I am unable to solve is that... when I want to compile/interpret(whatever u want to call) the DLThput.py/ULthput.py , it is showing the same error as above ... ValueError: Attempted relative import beyond toplevel package. Do I have any solution other adding paths to sys hacks? I really don't want to do that unless it's the only thing to do.
So, how can I dodge this?
You're running lteDebugger.py, which means that any "packages" must be at least one level lower in the directory tree - they need to be contained inside a folder for Python to recognize them as packages rather than modules (and thus for relative imports to work).
anomalyCheck is recognized as a package, but its parent directory is not (because that's where lteDebugger.py is), and thus you aren't allowed to use relative imports to go up to that parent directory.
One way you could fix this is by moving everything except lteDebugger.py into a subdirectory, e.g.:
Source/
debugger/
anomalyCheck/
__init__.py
DLthput.py
ULPowerStats.py
ULThput.py
config/
__init__.py
configure.py
parserTools/
__init__.py
logParser.py
utilities/
__init__.py
plotLogResults.py
__init__.py
lteDebugger.py
and then lteDebugger.py would do things like import debugger.anomalyCheck.DLthput.py.
Multilevel relative import
I have following folder structure
top\
__init__.py
util\
__init__.py
utiltest.py
foo\
__init__.py
foo.py
bar\
__init__.py
foobar.py
I want to access from foobar.py the module utiltest.py. I tried following relative import, but this doesn't work:
from ...util.utiltest import *
I always get
ValueError: Attempted relative import beyond toplevel package
How to do such a multileve relative import?
I realize this is an old question, but I feel the accepted answer likely misses the main issue with the questioner's code. It's not wrong, strictly speaking, but it gives a suggestion that only coincidentally happens to work around the real issue.
That real issue is that the foobar.py file in top\foo\bar is being run as a script. When a (correct!) relative import is attempted, it fails because the Python interpreter doesn't understand the package structure.
The best fix for this is to run foobar.py not by filename, but instead to use the -m flag to the interpreter to tell it to run the top.foo.bar.foobar module. This way Python will know the main module it's loading is in a package, and it will know exactly where the relative import is referring.
You must import foobar from the parent folder of top:
import top.foo.bar.foobar
This tells Python that top is the top level package. Relative imports are possible only inside a package.
So I am working on a Python project that was here before me in an SVN repo. When I first pulled it, the structure was a bit odd due to the fact that it was similar to:
Proj\
src\
tags\
trunk\
And then everything is inside src\ are the python module files except src\ turns out to just be a logical folder with no overall package inside. There isn't a __init__.py in the project anywhere. So I want to restructure it at least so I can use relative imports through my project. I also want to set it up so it looks more like this.
Proj\
src\
model\
controller\
view\
test\
tags\
trunk\
However, I tried setting this up and no matter what I seem to do, it cannot resolve the relative import the moment I have to traverse packages. I placed a __init__.py file in each level package including one inside the src\ folder with all of them having __all__ defined. However, when I try to make a unit test in my test\ package and do an import saying:
from ..model.foo import Foo
to attempt to import the Foo class from module foo.py located inside of the model package, it doesn't resolve. Just in case it was a problem specifically with unit tests, I also tried this with a module in the controller package that was dependent on a class in the model package and vice versa. None of them worked. How do I resolve this?
Have you added the root folder to your system path?
import sys
sys.path.append(<place the Proj dir here>)
then you could import as follows:
from src.model.somefile import Something
If you don't know the absolute path for Proj, you can always use combinations such as
os.path.dirname(os.getcwd())