Should I use
from foo import bar
OR
import foo.bar as bar
when importing a module and an
Both are technically different:
import torch.nn as nn will only import a module/package torch.nn, wheresfrom torch import nn can and will prefer to import an attribute .nn from the torch module/package. Importing a module/package torch.nn is a fall.back.In practice, it is bad style to have the same fully qualified name refer to two separate things. As such, torch.nn should only refer to a module/package. In this common case, both import statements are functionally equivalent: The same object is imported and bound to the same name.
Which one to choose comes down to preference if the target always is a module. There are practical differences when refactoring:
import torch.nn as nn guarantees .nn is a module/package. It protects against accidentally shadowing with an attribute.from torch import nn does not care what .nn is. It allows to transparently change the implementation.7.11. The import statement
The basic import statement (no from clause) is executed in two steps:
- find a module, loading and initializing it if necessary
- define a name or names in the local namespace for the scope where the import statement occurs.
[...]
The from form uses a slightly more complex process:
find the module specified in the from clause, loading and initializing it if necessary;
for each of the identifiers specified in the import clauses:
- check if the imported module has an attribute by that name
- if not, attempt to import a submodule with that name and then check the imported module again for that attribute