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

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

    I've just discovered one more subtle difference between these two methods.

    If module foo uses a following import:

    from itertools import count
    

    Then module bar can by mistake use count as though it was defined in foo, not in itertools:

    import foo
    foo.count()
    

    If foo uses:

    import itertools
    

    the mistake is still possible, but less likely to be made. bar needs to:

    import foo
    foo.itertools.count()
    

    This caused some troubles to me. I had a module that by mistake imported an exception from a module that did not define it, only imported it from other module (using from module import SomeException). When the import was no longer needed and removed, the offending module was broken.

提交回复
热议问题