-1

Are the following import statements equivalent: import mypack.mymod and from mypack import mymod in Python3?

Suppose I've the following directory directory hierarchy:

.
├── main.py
└── mypack
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-37.pyc
    │   └── mymod.cpython-37.pyc
    └── mymod.py

When importing the mymod module in main.py are the import mypack.mymod and from mypack import mymod statements equivalent? I've been experimenting with both, and they seem to perform the exact same job.

Shuzheng
  • 11,288
  • 20
  • 88
  • 186
  • They import the same module, but they import it under different names into your script…! – deceze May 06 '20 at 10:12
  • What do you mean by equivalent? It should be immediately observable that they bind the module to a different name, thereby not being equivalent. – MisterMiyagi May 06 '20 at 11:15
  • Does this answer your question? [Use 'import module' or 'from module import'?](https://stackoverflow.com/questions/710551/use-import-module-or-from-module-import) – Tomerikoo May 06 '20 at 11:19

2 Answers2

1

The two statements import the same module, but make it accessible through different identifiers. I will give examples using the os.path module:

import os.path

# Try accessing os.path.realpath
try:
    rp = os.path.realpath(".")
except NameError:
    print("!! Cannot access os.path")
else:
    print("OK", rp)

# Try accessing path.realpath
try:
    rp = path.realpath(".")
except NameError:
    print("!! Cannot access path")
else:
    print("OK", rp)

This yields:

OK C:\Users\ME\Documents
!! Cannot access path

Change the import in the first line to:

from os import path

And the output switches to:

!! Cannot access os.path
OK C:\Users\ME\Documents
Amitai Irron
  • 1,973
  • 1
  • 12
  • 14
1

Difference is w.r.t how package is available to use in your main.py. Let's take the three possible ways:

assume dir structure is same as yours and foo function is present in mymod.py


case 1:

# main.py
from mypack import mymod
if __name__ == '__main__':
    print(dir())
    mymod.foo()

This results in

['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'mymod']
bar

case 2:

# main.py
import mypack.mymod
if __name__ == '__main__':
    print(dir())
    mypack.mymod.foo()

This results in

['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'mypack']
bar

case 3:

# main.py
import mypack.mymod as md
if __name__ == '__main__':
    print(dir())
    md.foo()

This results in

['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'md']
bar

Observation:

As you can see when dirs is printed, the module in case 1 is available as mymod & thus you use foo as mymod.foo, in case 2 as mypack & thus to use foo you now have to use mypack.mymod.foo and last in case 3 as md & this to use foo you now have to use md.foo

akazuko
  • 1,394
  • 11
  • 19