Home > Backend Development > Python Tutorial > \'from ... import vs import ...: When to Use Which?\'

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

Barbara Streisand
Release: 2024-10-27 01:26:30
Original
685 people have browsed it

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>
Copy after login

and

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

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template