I am having trouble importing python modules in a different folder than the one I am using. I know there are a number of posts about this on StackOverflow, but I am still running into a few issues with importing. Here is my general file structure:
Folder
__init__.py
A.py
folder
__init__.py
B.py
tests
__init__.py
C.ipynb
I am trying to import B from C, but doing so gives me a number of errors. If I write
from folder import B
I get
ModuleNotFoundError: No module named 'folder'.
If I write
from . import B
I get
ImportError: attempted relative import with no known parent package.
If I write
from . import B
or
from .. import B
I get
ImportError: attempted relative import with no known parent package.
Additionally, if I try to import B from A, I also get errors. Running
import folder.B
or
from folder import B
gives
ModuleNotFoundError: No module named 'folder'.
Could someone help me import these files correctly? I know that modifying sys.path is an option (although I am not entirely sure how to implement this), but I feel like there must be a way to do this without modifying sys.path.
Thank you, and I apologize if this has been answered already!
Related
I know there are dozens of Python package import questions, but I can't seem to find an answer that works. Most answers seem to be about the missing __init__.py to make a package, but I've got one in the base of the project (and I've tried in the sub-folders as well).
I have a project of the form
package
+-- __init__.py
+-- weasel.py
+-- badgers
| +-- __init__.py
| +-- a.py
where weasel.py just contains a test function
def test_function():
return "HELLO"
and I want to be able to call test_function from a.py, I've attempted (all with and without the init.py in the folder badgers) and none of which seem to work.
import weasel -> ModuleNotFoundError: No module named 'weasel'
from . import weasel -> ImportError: attempted relative import with no known parent package
import package.weasel -> ModuleNotFoundError: No module named 'package'
from package import weasel
The hack I've managed to employ thus far, which works fine in Spyder and in my production environment; project is a Dash App (so Flask) deployed to render.
import sys
sys.path.append("..")
import weasel
But this just throws ModuleNotFoundError in VS Code.
I'm not adverse to a hack :S but the needs of the current project kinda make life much, much, easier if I could build the project in VS Code.
Please, I implore the stackoverflow community could someone please let me know what I'm doing wrong? Or a hack that will work in VS Code?
Thank you,
This is caused by the path. The path of vscode running file is not the current file path. You need to add it manually.
import sys
sys.path.append("your package's Path") #for example, my path is "C:/my_python/package"
import weasel
Here is my directory structure.
Tips:
Do not use "..", it will really adds two commas to path instead of parent directory.
My folder structure is
fold1/fold2/a.py
fold1/fold3/b.py
fold1/fold3/c.py
a.py is doing
from fold1.fold3 import c
c.py is doing
import b
When I run a.py, I am getting error "No module named b"
I have __init__.py in all folders, but still why I am getting that error.
I know that lastly python checks for packages in current directory, so here current directory is "fold2" and I am not finding "b.py" in that fold2? but both "c.py" and "b.py" are in same directories right but still why I am getting that error?
Edit: The code is generated by pyxb python module, so I cannot change import statements.
import b is an absolute import: b has to be found in a package listed in sys.path.
In order to import b relative to the package containing c, use the relative import
from . import b
. refers to the package containing c (fold3). .. would refer to the package containing that package (fold1). You could also write
from ..fold3 import b
.. refers to fold1, so ..fold3 refers to the module fold3 in the package fold1.
When using relative imports, it doesn't matter where fold1 exists: it could be in sys.path, it could be a submodule of some other package. As long as the internal structure of fold1 remains the same, the relative imports will continue to work the same.
All the paths are relative to where you start the interpreter from!
c.py is looking for b in the parent of fold1
try using a form like from fold1.fold3 import b instead
I have a custom python module I'm working on and am confused how I should import modules into other modules. I want to use bits and pieces of some modules within others and keep getting an error: ImportError: cannot import name NameOfModule
I'm assuming there's some sort of circular reference that's causing the issue but I'm not sure if I need to add something to __init__.py, or if there's a specific way of importing the modules into each other, or if I should change my folder structure?
If I want to be able to use some function from mod1.py within mod2.py how should I go about setting up the import statements?
My current folder structure is:
FolderName
-__init__.py
-mod1.py
-mod2.py
-mod3.py
-mod4.py
Sample code:
__init__.py is empty
mod1.py: from . import mod2
mod2.py: from . import mod1
You should be using relative imports for files within the current module, like so:
from . import mod2
Or:
from .mod2 import foo
And unless you have a VERY good reason, you should be using Python 3.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to do relative imports in Python?
I'm experiencing something that seems very random to me.
I have a folder structure much like this:
dir A
__init__.py is empty
a.py imports stuff and b.py
dir B
__init__.py is empty
b.py imports NOTHING
a.py raises an error (cannot import name b). This only happens while b is part of module B.
If I move it outside the directory, the import error does NOT occur.
Any help would be appreciated. I must be overlooking something.
Did you try the relative import
from ..B import b
?
EDIT: This does not apply if it doesn't matter where package B lives.
But you don't describe what exactly you do. As you may know or not, there are several import forms:
import module
import package # imports package.__init__ under the name package
import package.module
from package import module
import package
from module import component
from package.module import component
As you only write
a.py imports stuff and b.py
I don't know what exactly happens: if you try to
import b
that fails because b lives in the package B. So you need one of
from B import b
import B.b
Your comment above mentions a name clash. Which of two equally named packages and modules have priority depends on in which directory you are: '.' is normally at the very start of sys.path, so if you are directly under your utils directory you might have a different experience than otherwise.
First off all: I'm sorry, I know there has been lots of question about relative imports, but I just didn't find a solution. If possible I would like to use the following directory layout:
myClass/
__init__.py
test/
demo.py
benchmark.py
specs.py
src/
__init__.py
myClass.py
Now my questions are:
How do the test files from within the package properly import myClass.py?
How would you import the package from outside, assuming you take myClass as submodule in libs/myClass or include/myClass?
So far I couldn't find an elegant solution for this. From what I understand Guido's Decision it should be possible to do from ..src import myClass but this will error:
ValueError: Attempted relative import in non-package
Which looks as it doesn't treat myClass as packages. Reading the docs:
The __init__.py files are required to make Python treat the directories as containing packages;
It seems I'm missing something that specifies where the scripts of the package are, should I use .pth ?
ValueError: Attempted relative import in non-package
Means you attempt to use relative import in the module which is not package. Its problem with the file which has this from ... import statement, and not the file which you are trying to import.
So if you are doing relative imports in your tests, for example, you should make your tests to be part of your package. This means
Adding __init__.py to test/
Running them from some outside script, like nosetests
If you run something as python myClass/test/demo.py, relative imports will not work too since you are running demo module not as package. Relative imports require that the module which uses them is being imported itself either as package module, from myClass.test.demo import blabla, or with relative import.
After hours of searching last night I found the answer to relative imports in python!! Or an easy solution at the very least. The best way to fix this is to have the modules called from another module. So say you want demo.py to import myClass.py. In the myClass folder at the root of the sub-packages they need to have a file that calls the other two. From what I gather the working directory is always considered __main__ so if you test the import from demo.py with the demo.py script, you will receive that error. To illustrate:
Folder hierarchy:
myClass/
main.py #arbitrary name, can be anything
test/
__init__.py
demo.py
src/
__init__.py
myClass.py
myClass.py:
def randomMaths(x):
a = x * 2
y = x * a
return y
demo.py:
from ..src import myClass
def printer():
print(myClass.randomMaths(42))
main.py:
import test.demo
demo.printer()
If you run demo.py in the interpreter, you will generate an error, but running main.py will not. It's a little convoluted, but it works :D
Intra-package-references describes how to myClass from test/*. To import the package from outside, you should add its path to PYTHONPATH environment variable before running the importer application, or to sys.path list in the code before importing it.
Why from ..src import myClass fails: probably, src is not a python package, you cannot import from there. You should add it to python path as described above.