简体   繁体   中英

In python, what is the difference between 'import foo.bar as bar' and 'from foo import bar'?

I see this convention in pyTorch and matplotlib:

import torch.nn as nn
import torch.optim as optim

import matplotlib.pyplot as plt

Is there a reason why the whole path ( module.submodule ) is being imported as an alias instead of just the submodule? What is the difference if I import like this:

from torch import nn
from torch import optim

from matplotlib import pyplot as plt

Edit : So for the generic case:

import foo.bar as bar    # [1]
from foo import bar      # [2]

Can there exist code which refers to bar such that it will run with [1] and not [2] (and vice versa)? Ie is there functional difference between these two ways to import?

Behind the scenes, all of the import statements are essentially mapped to the builtin __import__ eg:

import torch.nn as nn

becomes

nn = __import__("torch.nn", globals(), locals(),  [], 0)

similarly:

from torch import nn

becomes

nn = __import__("torch", globals(), locals(), ["nn"], 0)

Subtly different but functionally equivalent.

Reference: https://docs.python.org/3/library/functions.html# import

import blank as blank lets you reference the module as that name throughout the program.

from blank import blank imports specific methods, functions, and classes from a module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM