search
HomeBackend DevelopmentPython TutorialSolution to the duplicate names of Python modules and packages

This article mainly introduces you to the method of handling modules and packages with the same name in Python. The introduction in the article is very detailed and has certain reference and learning value for everyone. Friends who need it can take a look below.

Preface

In programming development, I personally feel that as long as you follow the specifications, there will be few problems. . When you first start learning a technology, you will indeed encounter many pitfalls. It’s a good thing that you’ve stepped on more pitfalls. You’ll learn more, and you’ll feel more and more the importance of following the rules. The rules are formulated to avoid problems. Sometimes you really should listen to the advice of experienced people and don't go your own way. This does not seem to be the focus of this article. In fact, my focus is to express that we should try our best to do things according to the standards, so that we will avoid many detours.

The main programming language I use now is Python. After being exposed to Python so far, I feel that I have encountered very few pitfalls, and basically I have not encountered any strange problems. In fact, this is not a good thing. If you don’t step into the trap, you won’t understand many knowledge points lying in the dark, so it will be difficult to grow. Fortunately, there are some colleagues who know how to step into the trap.

A colleague asked me, in Python, if a module and a package have the same name, can only the package be imported? What should I do if I want to import the module? What he probably means is that in the same directory of the project, there is a foo.py file and a foo/ directory. If import foo is imported, the contents of foo/ will be imported instead of the contents of foo.py.

When I was asked this question, the first thing I felt was surprise. There was obviously ambiguity. If it were me, I would definitely not design the module name and package name to be the same, because essentially there is no way to distinguish who to import when importing. Unless the system has special provisions, for example, it is stipulated that only packages can be imported in this case.

I subconsciously think that an error should be reported here, because the Python interpreter does not know who to import. However, a colleague told me that other people's code is written like this, and in this case the package will be imported by default. That's possible, and the interpreter has stipulated that the package will always be imported in this case.

In order to verify this, I wrote a simple project with the following project structure:


.
├── main.py
└── same
 ├── api
 │ └── init.py
 ├── auth
 │ └── init.py
 ├── auth.py
 └── init.py

Among them:

same/api/init/py content:


##

from .. import auth

same/auth/init.py content:



auth_str = "This is str in package!"

Contents of same/auth.py: Contents of



auth_str = "This is str in module!"

main.py :


from future import print_function

from same.api import auth

# Script starts from here

if name == "main":
 print(auth.auth_str)

It’s a little complicated, haha, mainly because the general structure of my colleagues is like this, here it is for better simulation. I defined an

auth_str string in the same.auth package, and another in the same.auth module with the same name auth_str string with the same name, then try to import auth in the same.api package, and finally try to output same.api.auth.auth_str in main.py to see which string will is printed. At the same time, we tried to execute main.py with Python2 and Python3, and the results we got were:


This is str in package!

This verified that our conjecture was correct, and the interpreter did only import the package. content. However, I don't know if there is any official information stating that this is the case, so I am not sure if this is just a coincidence.

So, I started looking up information to verify this conclusion. Let me be honest. For someone whose English is so bad that you can’t even imagine it, I can only try to search for the answer on Baidu first. The fact is that using Baidu is often a pity. After a while, to no avail, I had no choice but to bite the bullet and try searching in English. So, I found the following question on stackoverflow:

How python deals with module and package having the same name?

One of them answered that the official Python documentation mentions when describing the module search path At this point: docs.python.org/3/tutorial/modules.html#the-module-search-path.

The document has the following description:

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.


That is to say, the directory will be searched first under the search path of the library, which means that the directory Will be loaded instead of the module with the same name.

I am finally relieved now, and my previous conclusion has been confirmed. In Python, if you try to import a module and package with the same name, the package will be imported. In this case, if you want to import the module, you may need to use some 'hack' methods. There are some examples in the stackoverflow post mentioned above. Of course, the best way is to avoid such a design, so that you won't spend so long looking up information, and you won't spend so long writing articles similar to this article.

Summary

[Related recommendations]

1. Special recommendation:"php Programmer Toolbox" V0.1 version download

2. Python free video tutorial

3. Python object-oriented video tutorial

The above is the detailed content of Solution to the duplicate names of Python modules and packages. 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
Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft