Imagine I have this structure :
dir/
__init__.py
dir1/
__init__.py
x.py
dir2/
__init__.py
y.py
Now I want to import x.py to y.py .
I try this from ..dir1.x import * in y.py from PEP 328 but I get this error Attempted relative import in non-package .
I search for hours but I can not find any answer to this problem .
There are a lot of similar problems like mine but none of them help me like this
Please help .
Thanks a lot .
in y.py, add this piece of import code
import sys
sys.path.insert(0, '..')
then do
from dir1.x import *
Relative imports won't work when files are invocated directly:
python y.py
since they have __name__ == '__main__' instead of their full package name.
For the relative import to work you must use y as a package:
python -m dir.dir2.y
Related
Let's say I have the following directory structure:
parent_dir/
foo_dir/
foo.py
bar_dir/
bar.py
If I wanted to import bar.py from within foo.py, how would I do that?
If all occurring directories are Python packages, i.e. they all contain __init__.py, then you can use
from ..bar_dir import bar
If the directories aren't Python packages, you can do this by messing around with sys.path, but you shouldn't.
You can use the sys and os modules for generalized imports. In foo.py start with the lines
import sys
import os
sys.path.append(os.path.abspath('../bar_dir'))
import bar
Let's say if you have following structure:
root
|_ productconst.py
|_ products
|_ __init__.py
And if you would like to import productconst in products.__init__, then following can be used :
from ..productconst import *
If you're having issues in python 3+, the following worked for me using sys.path.append("..").
sys.path.append("..")
from bar_dir import bar
My apps are organized like this:
apps/
code/
libglobal/
funglobal.py
tests/
project/
liblocal/
funlocal.py
main.py
In main.py I have:
import liblocal.funlocal
In funlocal.py I try to import funglobal.py with:
from ....code.libglobal import funglobal
When I run
python3 -B tests/project/main.py
I get an error:
from ....code.libglobal import funglobal
ValueError: attempted relative import beyond top-level package
I have read a lot of information about relative imports with python3 and still don't find how to solve this error without changing the apps organization radically. Any solution?
As the script being executed has its __name__ set as __main__ and defines itself to be on the top level of the package, it refuses to recognize scripts in sibling directories.
You can fix this with a sys.path hack:
import sys, os
sys.path.insert(0, os.path.abspath('../..'))
or an interseting alternative with setuptools is presented in this answer.
Have you a __init__.py script in each folder ?
If no, you should create an empty script named __init__.py in each folder.
I want to use relative import in Python 3.
My project:
main_folder
- __init__.py
- run.py
- tools.py
I want to have in run.py (MyClass declared in __init__.py):
from . import MyClass
And in run.py:
from .tools import my_func
An ImportError is raise.
Alternatively, with absolute import, debugging in PyCharm does not work and the library takes from installed packages, not my directory.
I know one way, but it is terrible:
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
How to use this import in my project?
When you use PyCharm, it automatically makes the current module main, so relative statements like from . import <module> will not work. read more here.
to fix your problem, put the __init__.py and tools.py files in a sub-directory
main_directory/
run.py
sub_directory/
__init__.py
tools.py
in your run.py file, write the following as your import statements
from sub_directory import tools
from sub_directory.__init__ import MyClass
Edit: as #9000 mentioned, you can write from sub_directory import MyClass and achieve the same thing.
Right,
I have a structure like so:
/Project
__init__.py
script_a.py
/tests
__init__.py
test_something.py
When test_something tries to import using from . import script_a it returns the error Attempted relative import in non-package.
I've put in the empty __init__.py files and added /Project to PYTHONPATH but it still throws up this error!
Any ideas?
EDIT:
I have now used a tester.py situated in \Project and call:
import script_a
from tests.test_something import *
Now it works!!
When test_something tries to import using from . import script_a it returns the error Attempted relative import in non-package.
Using one dot . will lead you to the current directory. You should use two dots .. to get to the parent dir.
You cannot run a module with a relative import itself. You can only import it. So test_something.py can only run as an import but it is not possible to run the script as __main__
from Project import script_a should work for you.
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.