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?
Allows you to reference the module under the
futures
namespace in your code (as opposed toconcurrent.futures
without theas
syntax). However, the typing is mostly redundant--you're importing something and declaring its name to be the exact same thing. The standard syntax for this type of import is thefrom <package> import <module>
.The salient point about your question is that the
as
syntax is mainly to support multiple imports of the same name without clobbering each other. For example.Anything else and you are abusing the
as
syntax and to me would be considered anti-pattern, because the language provided you a correct way to do what you wanted.There are a few functional differences. First, as already mentioned in the comments,
import package.thing as thing
requiresthing
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 forpackage
does not have athing
attribute, it will try to look upsys.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.