Python - import in if

后端 未结 4 1800
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 16:18

I wrote little wrapper for urllib (python3). Is it proper and safe to import module in if?

if self.response_encodi         


        
4条回答
  •  醉梦人生
    2020-12-15 16:52

    Is it safe? Yes. As Martijin's answer pointed out that Official Python use this.

    Is it proper? Depends. Python performance docs points out that even though python can avoid import the same module, there is still overhead.

    So i believe you should ask yourself, how often the if statement is true. If very often, then there will be large overhead, and you should import it at the beginning of the file. If not often, then import in if statement is a wise choice.

提交回复
热议问题