Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "from x.y import z" and "import x.y.z as z"

In situations where you want to import a nested module into your namespace, I've always written it like this:

from concurrent import futures

However, I recently realized that this can be expressed using the "as" syntax as well. See the following:

import concurrent.futures as futures

Which has the subjective advantage of looking more similar to other imports:

import sys
import os
import concurrent.futures as futures

... with the disadvantage of added verbosity.

Is there a functional difference between the two, or is one officially preferred in a PEP or otherwise?

like image 973
Velovix Avatar asked May 11 '18 19:05

Velovix


1 Answers

There are a few functional differences. First, as already mentioned in the comments, import package.thing as thing requires thing to be a module (or a subpackage, which is not actually a separate case because packages count as modules).

Second, in Python 3.5 and later, if from package import thing finds that the module object for package does not have a thing attribute, it will try to look up sys.modules['package.thing'] as a fallback. This was added to handle certain cases of circular relative imports. import package.thing as thing does not yet perform this handling, but it will in Python 3.7.

like image 112
user2357112 supports Monica Avatar answered Nov 19 '22 05:11

user2357112 supports Monica