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!