Home  >  Article  >  Backend Development  >  \"from ... import vs import ...: When to Use Which?\"

\"from ... import vs import ...: When to Use Which?\"

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 01:26:30596browse

from ... import vs import . Revisited

The question has arisen regarding the difference between the following code fragments:

<code class="python">from urllib import request</code>

and

<code class="python">import urllib.request</code>

To clarify, these two methods are not interchangeable. The decision between them depends on the desired accessibility of the imported entity.

Using from ... import allows direct access to the imported entity without specifying the module name. For instance,

<code class="python">from urllib import request
mine = request()</code>

On the other hand, import . requires specifying the module name when accessing the imported entity.

<code class="python">import urllib.request
mine = urllib.request()</code>

Additionally, from ... import allows for aliasing of imports to avoid collisions with built-in functions or other imported entities. For example,

<code class="python">from os import open as open_
mine = open_()</code>

This usage allows one to utilize os.open without overriding the built-in open() function that returns file handles. Ultimately, the choice between these import styles depends on the programmer's preference and the specific context of the code.

The above is the detailed content of \"from ... import vs import ...: When to Use Which?\". For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn