Home >Backend Development >Python Tutorial >How Have Python 3 Import Statements Changed from Python 2?

How Have Python 3 Import Statements Changed from Python 2?

Linda Hamilton
Linda HamiltonOriginal
2024-11-28 16:13:15810browse

How Have Python 3 Import Statements Changed from Python 2?

Evolution of Import Statements in Python 3

Python 3 has introduced significant changes to the import statement to promote clarity and avoid ambiguity.

Relative Imports

In Python 2, implicit relative imports within packages were widely used. This meant that modules could import from other modules within the same package without specifying the path. For example:

However, in Python 3, relative imports are no longer supported. Instead, explicit imports or absolute imports must be used. This helps prevent confusion about whether an import is relative or absolute.

Star Imports

Star imports, which import all symbols from a module using *, were allowed in Python 2 at both module and function level. However, in Python 3, star imports are only permitted at the module level. This helps improve readability and reduce potential namespace conflicts.

For example, in Python 2, the following was allowed:

In Python 3, this must be changed to:

By understanding these changes in import statements, developers can ensure their code is compatible with Python 3 and avoids ambiguity and potential errors.

The above is the detailed content of How Have Python 3 Import Statements Changed from Python 2?. 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