Use 'import module' or 'from module import'?

前端 未结 19 2480
一向
一向 2020-11-21 07:47

I\'ve tried to find a comprehensive guide on whether it is best to use import module or from module import. I\'ve just started with Python and I\'m

19条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 08:11

    Both ways are supported for a reason: there are times when one is more appropriate than the other.

    • import module: nice when you are using many bits from the module. drawback is that you'll need to qualify each reference with the module name.

    • from module import ...: nice that imported items are usable directly without module name prefix. The drawback is that you must list each thing you use, and that it's not clear in code where something came from.

    Which to use depends on which makes the code clear and readable, and has more than a little to do with personal preference. I lean toward import module generally because in the code it's very clear where an object or function came from. I use from module import ... when I'm using some object/function a lot in the code.

提交回复
热议问题