开发者

import inside or outside function [duplicate]

This question already has answers here: Closed 11 years ago.

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:

    1. standard library imports
    2. related third party imports
    3. 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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜