python - Why simple import of module in same directory is not allowed -
i've created 2 modules in same directory:
. ├── mod1.py ├── mod2.py
there no __init__.py
, don't want create package, i'm creating simple script have modularized breaking different modules.
my intention run mod1.py
using python mod1.py
~/junk/imports$ cat mod1.py . import mod2 print(mod2.some_expr) $ cat mod2.py some_expr = 'hello world!'
although know directly using import mod1
work, i'm deliberately not using module name doesn't clash built in modules (which felt practice)
i'm getting following errors python2
, 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> . 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> . import mod2 valueerror: attempted relative import in non-package
most of questions on stackoverflow deal packages, i'm not using packages. want run simple script.
my question not how it, want know reason behind above not working.
you shouldn't use relative, absolute import:
import mod2 print(mod2.some_expr)
the documentation pretty good, , so answers gives alternative using importlib
.
if handmade module clash builtin module, proper way go rename it, through addition of {pre,suf}fix. use importlib
.
the motivation underlying these limitation can found in pep 328, , comes bdfl preferences, on other solutions.
Comments
Post a Comment