This question is in context of python 2.7 and relative imports. I have gone through related questions and things are still not working for me. I don't know what am I missing here?
Following is my dir hierarchy
.
|-> wrapper.py
|-> __init__.py
|-> util
| |-> hello.py
| |-> __init__.py
|-> src
| |-> wrapper.py
| |-> __init__.py
All __init__.py are blank files only to "treat the directories as containing packages"
Following is how ./util/hello.py reads. This has its own main function and can run of its own.
#!/usr/bin/python
# This is hello.py.
import sys
# Define a main() function that prints a little greeting.
def main():
print "Hello World!!!"
# Standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
Following is how ./wrapper.py reads. This also has its own main function and uses ./util/hello.py to achieve its goal.
#!/usr/bin/python
# This is wrapper.py.
import sys
from util import hello
# Define a main() function that prints a little greeting.
def main():
hello.main() # This prints "Hello World!!!"
# Standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
Following is how ./src/wrapper.py reads.
#!/usr/bin/python
# This is wrapper.py.
import sys
from ..util import hello
# Define a main() function that prints a little greeting.
def main():
hello.main() # This prints "Hello World!!!"
# Standard boilerplate that calls the main() function.
if __name__ == '__main__':
main()
As you see, It's almost exact copy of ./wrapper.py with minimal changes to make it run (changes in import). All __init__.py are present too. However any attempt to run it gives following error.
Traceback (most recent call last):
File "wrapper.py", line 8, in <module>
from ..util import hello
ValueError: Attempted relative import in non-package
However, if I import hello.py as following it works:
import os
sys.path.append(os.path.abspath("../util/"))
import hello
Two Questions:
Q1. What am I doing wrong or what is missing my attention?
Q2. How can I code ./src/__init__.py such that just "import hello" works in ./src/wrapper.py?