8

I've always used from a import b but recently a team at work decided to move a module into a new namespace, and issued a warning notice telling people to replace import b with import a.b as b.

I've never used import as and the only documentation I can find seems to suggest it doesn't support import a.b as b, though clearly it does.

but is there actually a difference, and if so what?

Tom Tanner
  • 9,244
  • 3
  • 33
  • 61
  • 1
    https://stackoverflow.com/questions/22245711/from-import-or-import-as-for-modules answered here – Onk_r Jun 20 '18 at 08:15
  • damn, so there is. all the answers i could find were giving me 'import *' questions – Tom Tanner Jun 20 '18 at 08:18
  • There is a more important difference which the duplicate does not mention. from a import b imports any object, import a.b as b will only import a module/package/namespace. I have added an answer to the duplicate. – cdarke Jun 20 '18 at 10:35

2 Answers2

2

As far as I know, correct me if I am wrong.

First, import a.b must import a module(a file) or a package(a directory contains __init__.py).

For example, you can import tornado.web as web but you cannot import flask.Flask as Flask as Flask is an object in package flask.

Second, import a.b also import the namespace a which from a import b won't. You can check it by globals().

So what's the influence? For example:

import tornado.web as web

Now you have access to namespace tornado, but you cannot access tornado.options even though tornado has this module. But as python's global package management, if you from tornado import options, you will not only get access to options but also add it to namespace tornado. So now you can also access options by tornado.options.

Sraw
  • 18,892
  • 11
  • 54
  • 87
1

I am going to provide only a partial answer, and I will speculate a bit.

1) Sometimes I have observed that the second way works while the first does not. On my system:

Python 3.6.3 (default, Oct  3 2017, 21:45:48) 
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from tensorflow import keras   # <- this works
>>>
>>> import tensorflow.keras as K   # <- this fails
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'tensorflow.keras'
>>> 

2) I usually don't see a difference between these two approaches to importing. I haven't investigated WHY there is a difference with TensorFlow. It may have to do with what names are imported to the top level by the various TensorFlow subfolder init.py files (which are completely empty in most cases, but the one in ../dist_packages/tensorflow/python is pretty long).

John Ladasky
  • 1,016
  • 8
  • 17