Home >Backend Development >Python Tutorial >What are the Key Changes to Python 3\'s Import Statements Regarding Relative and Star Imports?

What are the Key Changes to Python 3\'s Import Statements Regarding Relative and Star Imports?

Susan Sarandon
Susan SarandonOriginal
2024-11-28 22:26:18496browse

What are the Key Changes to Python 3's Import Statements Regarding Relative and Star Imports?

Changes in Import Statement in Python 3: Understanding Relative and Star Imports

In Python 3, significant changes were made to the import statement to enhance clarity and avoid potential ambiguity. This article delves into these changes and explains their implications for programmers.

Relative Imports

Relative imports allow you to import modules relative to the current module's location. In Python 2, relative imports were implicitly allowed within packages. However, in Python 3, this feature has been deprecated. Absolute imports and explicit relative imports are now the supported options.

Absolute imports specify the module's full path, such as:

import mypackage.mymodule

Explicit relative imports use the . and .. syntax to specify the relative path, such as:

from .mymodule import MyModule

This path indicates that mymodule is in the same directory as the current module.

Star Imports

Star imports, which import all names from a module, were previously allowed at module level and within functions in Python 2. However, in Python 3, star imports are only permitted in module level code.

For example, in Python 2, you could import the entire math module within a function:

def sin_degrees(x):
    from math import *
    return sin(degrees(x))

In Python 3, this is no longer valid. Instead, you can either import the specific functions you need:

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

Or, you can import the entire module at module level:

from math import *

def sin_degrees(x):
    return sin(degrees(x))

These changes aim to promote clarity, reduce ambiguity, and enforce best practices in module and package management in Python 3 and beyond.

The above is the detailed content of What are the Key Changes to Python 3\'s Import Statements Regarding Relative and Star Imports?. 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