Hi
It's a naive question to find the correct synthax (all i tested failed):
Context: In
MyFile1.py
, i want to load the function1 and function2.
If all files are located in the current directory (traditional situation):
from MyFile1 import function1, function2
Now i move-up "MyFile1.py" into the upper directory:
from ..MyFile1 import function1, function2
Error:
ImportError: attempted relative import with no known parent package
Same error if i create a module:
MyModule.py
from MyFile1 import function1, function2
Then I call the module
from ..MyModule import function1, function2
What I'm missing (it supposed to be quite simple)?
Thanks
If the directory is in the same level as the executing file
from directory.mymodule import function
No: the executing file is not in the same directory.
- /MyFunctionsDirectory where
MyFile1.py
is
- /MyFunctionsDirectory/test where my executing file is and in which i want to import
function1
and function2
Well after digging into internet, I've found the below solution for my case by adding:
import sys
sys.path.append('../')
I'll need to go further to figure out (not so obvious topic).
That's because you are mistaking Python packages for directories. They are not the same thing, although directories are used to construct packages.
Relative imports are relative to Python packages, not to system directories.
If
function1
is in
MyPackage.MyLibrary
, then in
MyPackage.MyModule
you can use the relative import
from .MyLibrary import function1
and in
MyPackage.MySubpackage.MyModule
, you can use the relative import
from ..MyLibrary import function1
The
..
goes to the grandparent package, which has nothing to do with the grandparent directory.
Top take a little on the basic of understanding how a package work,this how i like to set it up.
project_env/
└── project/
├── __init__.py
├── foo/
│ └── bar.py
└── main.py
So
project
is the package folder,and this folder
most be in
sys.path
this i where Python will look for it.
I always have one
__init__.py
under prospect folder with content to bind package together and lift sub modules.
This make it easier to use the package.
Use the package:
G:\div_code
λ ptpython
>>> import projects
>>>
>>> projects.bar.answer_to_life()
42
>>> projects.main.main_func()
'Now in main func'
Or like import like this,goal is to make import easy to use.
>>> from projects import bar, main
>>>
>>> main.main_func()
'Now in main func'
>>> bar.answer_to_life()
42
Files in package.
__init__.py:
from . import main
from .foo import bar
main.py
def main_func():
return 'Now in main func'
bar.py
def answer_to_life():
return 42
Look this
Thread here talk about different ways how
sys.path
works,and add to it.
Thanks all for the explanations. Let me having a look on it and going back if i've additional questions.