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

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

    I personally always use

    from package.subpackage.subsubpackage import module
    

    and then access everything as

    module.function
    module.modulevar
    

    etc. The reason is that at the same time you have short invocation, and you clearly define the module namespace of each routine, something that is very useful if you have to search for usage of a given module in your source.

    Needless to say, do not use the import *, because it pollutes your namespace and it does not tell you where a given function comes from (from which module)

    Of course, you can run in trouble if you have the same module name for two different modules in two different packages, like

    from package1.subpackage import module
    from package2.subpackage import module
    

    in this case, of course you run into troubles, but then there's a strong hint that your package layout is flawed, and you have to rethink it.

提交回复
热议问题