Home Backend Development Python Tutorial What is the package in python? what's the effect? Introduction to packages in python

What is the package in python? what's the effect? Introduction to packages in python

Nov 20, 2018 pm 04:10 PM
python

This article brings you what is the package in python? what's the effect? The introduction of packages in python has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is a package?

Package is a way to organize the python module name space through ".module name". We wear Each folder can be called a package.

But please note that it is specified in python2. The __init__.py file must exist in the package.

The purpose of creating a package is not to run, but to be imported and used. A package is just a form, and the essence of a package is a module.

2. What is the function of a package?

It is essentially a folder, so the only function of a folder is to organize files. As more and more functions are written, we cannot put

all the functions in one folder, so we use modules to Organization function, as there are more and more modules, we need to use folders to organize module files to improve the structure and maintainability of the program.

Next Create some packages for later learning. Packages are easy to create. You only need a folder with __init__.py.

import os
os.makedirs('glance/api')
os.makedirs('glance/cmd')
os.makedirs('glance/db')
l = []
l.append(open('glance/__init__.py','w'))
l.append(open('glance/api/__init__.py','w'))
l.append(open('glance/api/policy.py','w'))
l.append(open('glance/api/versions.py','w'))
l.append(open('glance/cmd/__init__.py','w'))
l.append(open('glance/cmd/manage.py','w'))
l.append(open('glance/db/__init__.py','w'))
l.append(open('glance/db/models.py','w'))
map(lambda f:f.close() ,l)
Copy after login

Create the directory structure

We add some methods to each folder:

#policy.py
def get():
    print('from policy.py')
    
#versions.py
def create_resource(conf):
    print('from version.py: ',conf)
    
#manage.py
def main():
    print('from manage.py')
    
#models.py
def register_models(engine):
    print('from models.py: ',engine)
Copy after login

We can use the contents of the package in test.py, and when we import the package, we can use import or from xxx The form of import xxx

import glance.db.models
glance.db.models.register_models('mysql')
from glance.api.policy import get
get()
Copy after login

However, note: in the form of from xxx import xxx, "dot" cannot appear after the import. That is to say, from a.b import c is OK.

But from a import b.c is wrong

3.What does __init__.py do?

No matter which method we use to import a package, as long as it is the first time it is imported The package or any other part of the package will first execute the __init__.py file.

This file can be empty, but it can also store some initialization code.

Then we used before Can from xxx import * be used for package calls?

Yes, we need to give __all__ in the __init__.py file to determine the * imported content.

print("我是glance的__init__.py⽂件. ")
x = 10
def hehe():
    print("我是呵呵")
    
def haha():
    print("我是哈哈")
__all__ = ['x', "hehe"]
Copy after login

test.py

from glance import *
print(x) # OK
hehe() # OK
haha() # 报错. __all__⾥没有这个⻤东⻄
Copy after login

4. Relative import and absolute import

Our final package glance is written for others to use, and there will also be mutual imports within the glance package. At this time, there are two import methods: absolute import and relative import.

1). Absolute import: glance as the starting point

2). Relative import: use. Or. . As a starting point

For example, we use glance/cmd/manage.py in glance/api/version.py

# 在glance/api/version.py
#绝对导⼊
from glance.cmd import manage
manage.main()
#相对导⼊
# 这种情形不可以在versions中启动程序.
# attempted relative import beyond top-level package
from ..cmd import manage
manage.main()
Copy after login

We should pay attention when testing, the python package path is the same as The directory where the running script is located is related.

In python, the program you run is not allowed to exceed the scope of the current package (relative import).

If you use absolute import, there is no such problem. .That is, if you use relative import in the package, then when using the information in the package, you can only import it outside the package

# 在policy.py
import versions
Copy after login

If the entry of our program is policy, Then there is no problem with the program at this time. But if we import the policy in glance outside glance, an error will be reported.

The reason is that if we access it from outside When setting policy, the path in .sys.path is outside. Therefore, the versions module cannot be found directly. Therefore, an error will definitely be reported:

ModuleNotFoundError: No module named 'versions'
Copy after login
When we make an error in importing the package, we must First look at sys.path. See if you can really get the package information.

5. Import a package separately

# 在test.py中
import glance
Copy after login

The imported glance cannot do anything at this time. Because in glance There is no loading of sub-packages in __init__.py. At this time, we need to introduce the contents of the sub-packages in __init__.py respectively.

1. Use relative paths

2. Notes on using absolute paths to

packages:

The import statements related to packages are also import and from xxx import xxx, but no matter which one is used, no matter where it is , one principle must be followed when importing: For any import with a dot, the left side of the

dot must be a package. Otherwise, an error will be reported. You can bring a series of dots. For example: from a.b.c import d

The above is the detailed content of What is the package in python? what's the effect? Introduction to packages in python. 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)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

See all articles