Import statement inside class/function definition - is it a good idea?

前端 未结 6 1518
醉梦人生
醉梦人生 2020-12-05 17:18

I created a module named util that provides classes and functions I often use in Python. Some of them need imported features. What are the pros and the cons of

6条回答
  •  孤街浪徒
    2020-12-05 17:48

    PEP8, the Python style guide, states that:

    Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

    Of course this is no hard and fast rule, and imports can go anywhere you want them to. But putting them at the top is the best way to go about it. You can of course import within functions or a class.

    But note you cannot do this:

    def foo():
        from os import *
    

    Because:

    SyntaxWarning: import * only allowed at module level
    

提交回复
热议问题