If this is my directory tree
0 directories, 2 files
"""Initializes the module"""
CONSTANT = 1
sys.exit("what is happening here")
# from . import CONSTANT
# from temp import CONSTANT
if __name__ == "__main__":
print "This should never run"
This should never run
from . import CONSTANT
from temp import CONSTANT
You should be running it from out of the
temp directory. If
someDir contains your
temp directory, then:
someDir $ python -m temp #someDir/temp/__init__.py is your file.
On running python . in the temp directory I get the output This should never run, shouldn't the module be initialized first with the init.py file resulting in the abort?
If you run it from outside,
__init__.py will be called. And
sys.exit will be called too.
Second how do I go about doing imports in python modules? Neither of the two options I have mentioned above works. I can neither do from . import CONSTANT nor from temp import CONSTANT in the code above. What is the right way to do relative imports?
You are doing it just fine. Just import sys in your
__init__.py file. And fix the spelling of
Also why do I need the -m flag? Isn't it ok to just do python temp from the parent directory of temp?
You need the
-m flag to tell that you are using packages. If you dont use it you wont be able to do relative imports.