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

后端 未结 9 2010

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:26

    You may be interested in Stack Overflow question Why does 'import x;x.y' behave different from 'from x import y', and the first one fails when package x.init is not completed?.

    0 讨论(0)
  • 2021-02-04 15:32

    I believe in newer versions of Python (2.5+? must check my facts...) you can even do:

    import some_other_module as some_module
    

    So you could still go with style 1 and swap in a different module later on.

    I think it generally maps to how much you want to clutter up your namespace. Will you just be using one or two names in the module? Or all of them (from x import * is not allways bad, just generally)?

    0 讨论(0)
  • 2021-02-04 15:34

    I find that the notation

    from some_module import some_symbol
    

    works best in most cases. Also, in case of name clash for the symbol, you can use:

    from some_module import some_symbol as other_symbol
    

    As the question states, it avoids rewriting the module name all the time, each time with a risk of mistyping it. I use the syntax:

    import  module [as other_module]
    

    Only in two cases:

    1. I use too many of the module functions/objects to import them all
    2. The module defines some symbol that may change during execution
    0 讨论(0)
提交回复
热议问题