'from X import a' versus 'import X; X.

2019-03-13 08:05发布

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.

9条回答
何必那么认真
2楼-- · 2019-03-13 09:05

I believe in newer versions of Python (2.5+? must check my facts...) you can even do:

import some_other_module as some_module

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)?

查看更多
干净又极端
4楼-- · 2019-03-13 09:09

I tend to use only a few members of each module, so there's a lot of

from john import cleese
from terry import jones, gilliam

in my code. I'll import whole modules (such as os or wx) 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.

import michael
import sarah

import wave

gov_speech = wave.open(sarah.palin.speechfile)
parrot_sketch = wave.open(michael.palin.justresting)

(I could use from wave import open as wave_open, but I figure that wave.open will be more familiar to the reader.

查看更多
登录 后发表回答