Home > Backend Development > Python Tutorial > How Have Python 3\'s Import Statement Enhancements Improved Code Clarity and Reduced Ambiguity?

How Have Python 3\'s Import Statement Enhancements Improved Code Clarity and Reduced Ambiguity?

Barbara Streisand
Release: 2024-12-08 16:06:17
Original
378 people have browsed it

How Have Python 3's Import Statement Enhancements Improved Code Clarity and Reduced Ambiguity?

Understanding Import Statement Enhancements in Python 3

Background:

The Python 3 development team implemented changes to the import statement in Python 2, aimed at improving its clarity and reducing ambiguity.

Relative Imports:

  • What is a relative import?

    • When importing a module within a package that is relative to the current script or package.
  • Example:

    • In the example directory structure, derived.py would previously import BaseThing from base.py using the statement:

      from base import BaseThing
      Copy after login
    • Python 3 requires explicit relative imports:

      from .base import BaseThing
      Copy after login
    • The .base prefix explicitly indicates importing from the module directory of the current module.

Star Imports:

  • Restrictions in Python 3:

    • Star imports (e.g., from x import *) are only permitted in module-level code.
  • Use Case in Python 2:

    • In Python 2, star imports were allowed within functions to import multiple specific functions or classes at once.
  • Example:

    • In Python 2, the following code was valid:

      def sin_degrees(x):
          from math import *
          return sin(degrees(x))
      Copy after login
    • Python 3 requires a more explicit approach:

      def sin_degrees(x):
          from math import sin, degrees
          return sin(degrees(x))
      Copy after login

The above is the detailed content of How Have Python 3's Import Statement Enhancements Improved Code Clarity and Reduced Ambiguity?. 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