Difference between “from x.y import z” and “import x.y.z as z”

前端 未结 2 1727
感动是毒
感动是毒 2021-01-08 01:06

In situations where you want to import a nested module into your namespace, I\'ve always written it like this:

from co         


        
相关标签:
2条回答
  • 2021-01-08 01:40
    import concurrent.futures as futures
    

    Allows you to reference the module under the futures namespace in your code (as opposed to concurrent.futures without the as syntax). However, the typing is mostly redundant--you're importing something and declaring its name to be the exact same thing. The standard syntax for this type of import is the from <package> import <module>.

    The salient point about your question is that the as syntax is mainly to support multiple imports of the same name without clobbering each other. For example.

    from concurrent import futures
    from other.module import futures as my_futures
    

    Anything else and you are abusing the as syntax and to me would be considered anti-pattern, because the language provided you a correct way to do what you wanted.

    0 讨论(0)
  • 2021-01-08 01:56

    There are a few functional differences. First, as already mentioned in the comments, import package.thing as thing requires thing to be a module (or a subpackage, which is not actually a separate case because packages count as modules).

    Second, in Python 3.5 and later, if from package import thing finds that the module object for package does not have a thing attribute, it will try to look up sys.modules['package.thing'] as a fallback. This was added to handle certain cases of circular relative imports. import package.thing as thing does not yet perform this handling, but it will in Python 3.7.

    0 讨论(0)
提交回复
热议问题