loki
loki

Reputation: 972

Why can't I import using alias? Ex: `from tf import keras`

I would simply like to understand why a call for keras like from tf import keras will not work in the following code, while I am already importing tensorflow as tf in the first line?

import tensorflow as tf
from tf import keras

Error:

ModuleNotFoundError: No module named 'tf'

However, the following would work -

import tensorflow as tf
from tensorflow import keras

Thanks!

Upvotes: 2

Views: 237

Answers (1)

Yann Vernier
Yann Vernier

Reputation: 15887

This is because the import statement is responsible for finding your modules in the first place. It doesn't look in your current name space for variable bindings, which is where the alias tf is stored. This can also be thought of as your alias never renaming the target module:

>>> import sys as s
>>> s.__name__
'sys'

If keras is already an available name (as if any code had done import tensorflow.keras), you can still find that name within the imported module, so you could do something like keras = tf.keras then.

You can think of import foo as bar as a combination of import foo ; bar = foo ; del foo, except it never actually used the name foo in your local namespace.

It is possible, but quite awkward, to find the submodule using the given alias as well:

import importlib
import sys

import http as h
# Module name lookup method 1:
name = [k for (k,v) in sys.modules.items() if v is h][0]
# Module name lookup method 2:
name = h.__name__
c = importlib.import_module('.client', name)

Method 1 searches all currently imported modules to find the one that is h, which produces its imported (not just local) name, and uses a relative import from that. Quite likely method 2 also suffices, but it may not in case e.g. that entry has been deleted.

Upvotes: 4

Related Questions