Possible Duplicate:
Should Python import statements always be at the top of a module?
In a very simple one-file python program like
# ------------------------
# place 1
# import something
def foo():
# place 2
# import something
return something.foo()
def bar(f):
...
def baz():
f = foo()
bar(f)
baz()
# ----------------
Would you put the "import something" at place 1 开发者_开发技巧or 2?
PEP 8 specifies that:
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
Imports should be grouped in the following order:
- standard library imports
- related third party imports
local application/library specific imports
You should put a blank line between each group of imports.
Put any relevant all specification after the imports.
I'd principally agree with Robert S. answer, but sometimes it makes sense to put it into a function. Especially if you want to control the importing mechanism. This is useful if you cannot be sure if you actually have access to a specific module. Consider this example:
def foo():
try:
import somespecialmodule
# do something
# ...
except ImportError:
import anothermodule
# do something else
# ...
This might even be the case for standard library modules (I especially have in mind the optparse
and argparse
modules).
精彩评论