'from X import a' versus 'import X; X.a'

后端 未结 9 2005

I\'ve seen some Python programmers use the following style fairly consistently (we\'ll call it style 1):

import some_module
# Use some_module.some_identifier in          


        
9条回答
  •  太阳男子
    2021-02-04 15:23

    There are uses for both cases, so I don't think this is an either-or issue. I'd consider using from module import x,y,z when:

    • There are a fairly small number of things to import

    • The purpose of the functions imported is obvious when divorced from the module name. If the names are fairly generic, they may clash with others and tell you little. eg. seeing remove tells you little, but os.remove will probably hint that you're dealing with files.

    • The names don't clash. Similar to the above, but more important. Never do something like:

       from os import open
      

    import module [as renamed_module] has the advantage that it gives a bit more context about what is being called when you use it. It has the disadvantage that this is a bit more cluttered when the module isn't really giving more information, and is slightly less performant (2 lookups instead of 1).

    It also has advantages when testing however (eg. replacing os.open with a mock object, without having to change every module), and should be used when using mutable modules, e.g.

    import config
    config.dburl = 'sqlite:///test.db'
    

    If in doubt, I'd always go with the import module style.

提交回复
热议问题