Curious Curious - 6 months ago 14
Python Question

python module and imports

If this is my directory tree

temp
├── __init__.py
└── __main__.py

0 directories, 2 files


And I have the following code in
__init__.py
and in
__main__.py


__init__.py



"""Initializes the module"""

CONSTANT = 1
sys.exit("what is happening here")


__main__.py



# from . import CONSTANT
# from temp import CONSTANT
if __name__ == "__main__":

print "This should never run"


I am getting two problems here that I am trying to figure out

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?

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?

I am running this on Python 2.7.5, apologies if this has already been asked before.

Answer

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 CONSTANT.


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.