Home Backend Development Python Tutorial Solution to the duplicate names of Python modules and packages

Solution to the duplicate names of Python modules and packages

May 13, 2017 pm 01:43 PM
python Bag module

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
Copy after login

Among them:

same/api/init/py content:


##

from .. import auth
Copy after login

same/auth/init.py content:



auth_str = "This is str in package!"
Copy after login

Contents of same/auth.py: Contents of



auth_str = "This is str in module!"
Copy after login

main.py :


from future import print_function

from same.api import auth

# Script starts from here

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

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!
Copy after login
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 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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

See all articles