Home  >  Article  >  Backend Development  >  How to Import from the Standard Library When a Project Module Has the Same Name?

How to Import from the Standard Library When a Project Module Has the Same Name?

DDD
DDDOriginal
2024-11-07 05:44:02880browse

How to Import from the Standard Library When a Project Module Has the Same Name?

Import from Standard Library When Project Module Has Same Name (Controlling Python's Module Search Path)

Python's versatile import system enables importing modules from the standard library as well as from within project directories. However, conflicts may arise when a module in the project has the same name as a standard library module.

Problem:

Unable to import the standard library Calendar class from within a project containing a calendar module, causing errors. Attempting from calendar import Calendar imports from the project module instead.

Solution (Absolute Import):

Avoid renaming modules. Instead, leverage Python's absolute import feature, available in Python 2.5 and above:

from __future__ import absolute_import
import socket

In Python 3.x, absolute import is the default behavior. Pylint may raise warnings, but the code is valid.

Explanation:

Absolute import explicitly specifies where Python should look for modules, overriding the default search path that typically includes the project directory. By declaring absolute_import, Python searches the standard library before considering project modules with the same name.

The above is the detailed content of How to Import from the Standard Library When a Project Module Has the Same Name?. 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