Use and usefulness of the as syntax

Tim Chase python.list at tim.thechases.com
Sat Nov 12 07:43:06 EST 2011


On 11/12/11 05:56, candide wrote:
> First, could you confirm the following syntax
>
> import foo as f
>
> equivalent to
>
> import foo
> f = foo

and the issuing "del foo"


> Now, I was wondering about the usefulness in everyday programming of the
> as syntax within an import statement. Here are some instances retrieved
> from real code of such a syntax
>
> import numpy as np
> import math as _math
> import pickle as pickle
>
> -- In the last case, I can see no point

Without context, I'm guessing the last one is merely keeping 
parity in a block that reads:

   try:
     import cPickle as pickle
   except ImportError:
     import pickle as pickle



> So what is the pragmatics of the as syntax ?

The most common use-case I see is your first:  to shorten a 
frequently-used namespace.  I do this frequently with

   import Tkinter as tk

which makes it obvious where things are coming from.  I hate 
trying to track down variable-names if one did something like

   from Tkinter import *


The second big use case I see regularly is the full example 
(above):  try to import a faster/native module that shares an 
interface with a pure-python implementation.  However in the 
above, the "import pickle as pickle" is a uselessly redundant.

-tkc





More information about the Python-list mailing list