Is there a difference between `import a as b` and `import a ; b = a`?

Question:

It’s common for me to write in REPL, for example:

from datetime import datetime as dt

Is there a difference between this sentence and

from datetime import datetime
dt = datetime

? For now I can list two:

  • the first sentence is more readable
  • the first sentence does not create a datetime variable

PS: I’m trying to play with pyPEG for creating a toy parser.

Asked By: Marco Sulla

||

Answers:

In your second example, you don’t do del datetime like in the PEP, so datetime will remain a valid name, while in the first example, it is not. If you were to run del datetime, then they’d be identical.

The import as syntax was introduced in PEP 221. The second code example you provided is almost the same as the provided rationale for the change:

This PEP proposes an extension of Python syntax regarding the import and from import statements. These statements load in a module, and either bind that module to a local name, or binds objects from that module to a local name. However, it is sometimes desirable to bind those objects to a different name, for instance to avoid name clashes. This can currently be achieved using the following idiom:

import os
real_os = os
del os

Essentially, import as is just syntactic sugar and doesn’t do anything else special.

Answered By: Michael M.