[TSBOAPOOOWTDI]using names from modules

Terry Reedy tjreedy at udel.edu
Sat Nov 4 20:57:03 EDT 2017


On 11/4/2017 3:42 PM, Stefan Ram wrote:
>    What is better:
> 
> ...
> import math
> ...
> ... math.cos ...
> ...
> 
>    or
> 
> ...
> from math import cos
> ...
> ... cos ...
> ...
> 
>    ?
> 
>    (To me, the first is more readable, because at the site
>    where »math.cos« is used, it is made clear that »cos«
>    comes from math. But I assume that the second might use
>    one less name lookup and therefore is faster. What is the
>    one way to do it?)

There is no 'one way', which is why there is more than one way.
The first lets the reader know the source at each use site.
The second lets the reader know what use is made of the source at the 
top.  The advantage depends on how familiar the *reader* is with the 
source module and the functions therein.

Is your question generic to any module and object,  or specific to the 
math module?  If generic, and mode is part of the package you are 
writing, then 'import mod' is less likely to create a circular import 
error.  On the other hand, 'from mod import obj' is better for testing 
because it lets one mock obj in the importing module without touching 
the imported module (where the original may be internally needed in the 
same test).  With idlelib, there are both circular import and testing 
issues.

If importing a module is expensive in some way, then knowing that B only 
needs one or two 'cheap' items from A is needed may suggest a workaround 
or refactoring.  For instance, move items from  A to B and reverse the 
import between them.

Replacing an existing 'from tkinter import *' with 'import tkinter' or 
'import tkinter as tk' requires prefixing every existing reference to a 
tkinter object.  Replacing the same with 'from tkinter import Tk, ...' 
requires list each object.  The latter localizes the patch.  Plus see 
the preceding paragraphs.  In either case, complete enough test coverage 
is needed to make the change.

I initially started with the 'as tk' replacement, but switched to the 
list version.  A tkinter-specific reason was planning to switch from tk 
to ttk versions of widgets.  Moving, for instance, 'Button' from the 
tkinter list to the tkinter.ttk list, instead of changing prefixes, 
would be both easy and make it obvious, at the top, that the change had 
been made, and for all Buttons.

-- 
Terry Jan Reedy





More information about the Python-list mailing list