Search code examples
pythonpython-3.xpython-import

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)? I.e. is there functional difference between these two ways to import?


Solution

  • 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).nn
    

    As for matplotlib:

    import matplotlib.pyplot as plt
    # becomes
    plt = __import__("matplotlib.pyplot", globals(), locals(), [], 0)
    
    from matplotlib import pyplot as plt
    # becomes
    plt = __import__("matplotlib", globals(), locals(), ['pyplot'], 0).pyplot
    

    Subtly different but functionally equivalent.

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