I try to use __init__.py.
My directory:
sam@sam-M51Kr:~/code/python$ tree
.
|-- __init__.py
|-- lib
| |-- __init.py
| |-- sam_lib.py
| `-- sam_lib.pyc
`-- test.py
1 directory, 5 files
sam@sam-M51Kr:~/code/python$
All my __init__.py are empty.
My lib/sam_lib.py:
k='hello!'
My test.py:
import python.lib.sam_lib
print(sam_lib.k)
When I run:
sam@sam-M51Kr:~/code/python$ python test.py
Traceback (most recent call last):
File "test.py", line 1, in <module>
import python.lib.sam_lib
ImportError: No module named python.lib.sam_lib
sam@sam-M51Kr:~/code/python$
How to solve it with syntax import x.x?
Should I use __init.py__?
==============================
I revise lib/__init.py to lib/__init__.py
I try to revise test.py:
from . import lib.sam_lib as sam_lib
print(sam_lib.k)
It will cause an error:
sam@sam-M51Kr:~/code/python$ python test.py
File "test.py", line 1
from . import lib.sam_lib as sam_lib
^
SyntaxError: invalid syntax
sam@sam-M51Kr:~/code/python$
And it is ok when I revise to:
import lib.sam_lib as sam_lib
print(sam_lib.k)
Your code is wrong at different levels
__init.pyshould be__init__.pyimport a.b.cthec.xobject must be accessed usinga.b.c.xunless you usedimporta.b.c as c
To fix the code, use:
Note that
import python.lib.sam_lib as sam_liborfrom .lib import sam_libwould have worked if test.py is imported as a module as inimport python.testfrom a code in the upper level directory, not when you run test.py directly.