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

前端 未结 19 2187
一向
一向 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:14

    As Jan Wrobel mentions, one aspect of the different imports is in which way the imports are disclosed.

    Module mymath

    from math import gcd
    ...
    

    Use of mymath:

    import mymath
    mymath.gcd(30, 42)  # will work though maybe not expected
    

    If I imported gcd only for internal use, not to disclose it to users of mymath, this can be inconvenient. I have this pretty often, and in most cases I want to "keep my modules clean".

    Apart from the proposal of Jan Wrobel to obscure this a bit more by using import math instead, I have started to hide imports from disclosure by using a leading underscore:

    # for instance...
    from math import gcd as _gcd
    # or...
    import math as _math
    

    In larger projects this "best practice" allows my to exactly control what is disclosed to subsequent imports and what isn't. This keeps my modules clean and pays back at a certain size of project.

提交回复
热议问题