I've created two modules in the same directory:
.
├── mod1.py
├── mod2.py
There is no __init__.py
, I don't want to create this as a package, I'm just creating a simple script which I have modularized by breaking into different modules.
My intention is to run mod1.py
using python mod1.py
~/junk/imports$ cat mod1.py
from . import mod2
print(mod2.some_expr)
$ cat mod2.py
some_expr = 'hello world!'
Although I know that directly using import mod1
will work, but I'm deliberately not using it so that my module name doesn't clash with built in modules (which I felt is a good practice)
I'm getting the following errors with python2
and python3
~/junk/imports$ python3 --version
Python 3.4.3
kartik@kartik-lappy:~/junk/imports$ python3 mod1.py
Traceback (most recent call last):
File "mod1.py", line 1, in <module>
from . import mod2
SystemError: Parent module '' not loaded, cannot perform relative import
~/junk/imports$ python2 --version
Python 2.7.11
~/junk/imports$ python2 mod1.py
Traceback (most recent call last):
File "mod1.py", line 1, in <module>
from . import mod2
ValueError: Attempted relative import in non-package
Most of the questions like this on StackOverflow deal with packages, but I'm not using packages. I just want to run it as a simple script.
My question is not about how to do it, but I want to know the reason behind the above not working.