I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):
import some_module
# Use some_module.some_identifier in various places.
For support of this style, you can cite the "explicit is better than implicit" maxim. I've seen other programmers use this style (style 2):
from some_module import some_identifier
# Use some_identifier in various places.
The primary benefit that I see in style 2 is maintainability -- especially with duck typing ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the "readability counts" maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.
Addendum: It was noted that you could use as
to solve the switch from some_module
to some_other_module
in style 1. I forgot to mention that it is also common to decide to implement some_identifier
in your current module, which makes creation of an equivalent some_module
container slightly awkward.
I believe in newer versions of Python (2.5+? must check my facts...) you can even do:
So you could still go with style 1 and swap in a different module later on.
I think it generally maps to how much you want to clutter up your namespace. Will you just be using one or two names in the module? Or all of them (
from x import *
is not allways bad, just generally)?You may be interested in Stack Overflow question Why does 'import x;x.y' behave different from 'from x import y', and the first one fails when package x.init is not completed?.
I tend to use only a few members of each module, so there's a lot of
in my code. I'll import whole modules (such as
os
orwx
) if I expect to be using most of the module and the module name is short. I'll also import whole modules if there is a name conflict or I want to remind the reader what that function is associated with.(I could use
from wave import open as wave_open
, but I figure thatwave.open
will be more familiar to the reader.