Table of Contents
What is a package?
Create Python package
Third Party Software Package
Search path
Exploring the Standard Library
PyPI
浏览 PyPI
安装软件包
最佳实践
结论
Home Backend Development Python Tutorial Explore the use of Python packages

Explore the use of Python packages

Sep 02, 2023 pm 12:25 PM

探索 Python 包的使用

Python packages allow you to break up large systems and organize their modules in a consistent way so that you and others can use and reuse them efficiently. Python's motto "battery built in" means that it comes pre-installed with many useful packages in the standard library.

But you can also take advantage of many amazing third-party software packages. In this tutorial, you'll learn everything you need to know about what exactly a package is, how to import modules from a package, explore the built-in packages in the Python standard library, and install third-party packages.

What is a package?

Before discussing packages, let’s discuss modules first. A module is a source file with *.py extension where you (and others) place the functions and classes that make up your program.

A package in Python is just a folder containing multiple Python files, and there should be an __init__.py file. The __init__.py file indicates that the directory is a package. __init__.py The file can be empty or contain some executable code.

Package is the embodiment of Python's hierarchical namespace concept. Quoting the Zen of Python:

"Namespaces are a great idea - let's do more of them!"

To view the entire Python Zen, enter import this:

in a Python interactive session
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
>>> 
Copy after login

Namespaces help organize code and prevent naming conflicts. This is crucial when multiple people are working together or using packages developed by others.

While a package represents a hierarchy of subpackages and modules (which are files), the hierarchy does not have to be based on a file system, where packages and subpackages are directories and subdirectories. It's much more flexible than that.

Create Python package

Let's start with a simple example. Below we have a package called simple_package which contains two Python modules.

simple_package
.
├── __init__.py
├── tasks.py
└── views.py

0 directories, 3 files
Copy after login
  • __init__.py: Indicates that it is a package
  • tasks.py and views.py are modules

Third Party Software Package

Let’s take a look at the package named ansible. It is not a package in the standard library. You'll see later how to find and install third-party packages. Now, let's take a look at the directory file structure.

These packages are typically installed into the Python interpreter's site-packages directory, somewhere under lib (depending on version, operating system, and distribution).

For example, on a Mac, Python 3.10 would be located in /lib/python3.10/site-packages. Here's how ansible packages are organized:

tree ansible -L 1
ansible
├── cli
├── collections
├── compat
├── config
├── constants.py
├── context.py
├── errors
├── executor
├── galaxy
├── __init__.py
├── inventory
├── keyword_desc.yml
├── __main__.py
├── modules
├── module_utils
├── parsing
├── playbook
├── plugins
├── __pycache__
├── release.py
├── template
├── utils
├── vars
└── _vendor

18 directories, 6 files
Copy after login

There are 6 modules and 18 directories. Each directory is a sub-package of the main ansible package. Looking at the ansible/utils directory, we can see that it contains other modules and even a sub-package:

tree ansible/utils -L 1
ansible/utils
├── cmd_functions.py
├── collection_loader
├── color.py
├── context_objects.py
├── display.py
├── encrypt.py
├── fqcn.py
├── galaxy.py
├── hashing.py
├── helpers.py
├── __init__.py
├── jsonrpc.py
├── _junit_xml.py
├── listify.py
├── lock.py
├── multiprocessing.py
├── native_jinja.py
├── path.py
├── plugin_docs.py
├── py3compat.py
├── sentinel.py
├── shlex.py
├── singleton.py
├── ssh_functions.py
├── unicode.py
├── unsafe_proxy.py
├── vars.py
└── version.py

1 directory, 27 files

Copy after login

Search path

When you import a module, Python will perform a search algorithm based on the search path, which is the list of directories to start searching. The search path is a list of directories available through sys.path, and you can dynamically manipulate it (add, delete, or move items in the search path). The site-packages directory always exists.

To import the path.py module from ansible/utils you need to use the following command:

import ansible.utils.path
Copy after login

To import the path and encrypt modules, use the following command:

import ansible.utils.path
import ansible.utils.encrypt
Copy after login

If you also want to use the standard os.path module, you would use the following command:

import os.path
Copy after login

Now you can use one or both of the path modules without conflicting due to the namespace they belong to.

Exploring the Standard Library

The standard library has many packages. Whenever you need to complete a task but aren't sure how, it's worth exploring it. For any common task, such as math, shell integration, operating system integration, string manipulation, networking, and common file formats, there is most likely a well-designed, well-performing, and well-tested package in the standard library.

You can really trust the standard library packages, because getting into the standard library is a big deal. The package was either designed by core Python developers or was heavily vetted and used heavily in the field as a third-party library before making it into the standard library.

The following are all packages in the standard library organized by topic.

PyPI

The standard library is great, but often there are special features you need that are not standard. This doesn't mean you have to write it from scratch. Python has a vibrant and active community that develops and shares large amounts of code for free. Enter PyPI: The Python Package Index. PyPI hosts all publicly available software packages and provides a one-stop shop for browsing them.

浏览 PyPI

PyPI 将包组织在可浏览的索引中。您可以按主题、环境、框架、开发、状态、目标受众、许可证、自然语言、编程语言(是的,有支持多种编程语言的 Python 包)和操作系统来浏览和搜索。

截至 2021 年,PyPI 不再显示软件包的下载统计信息,因为维护统计信息所需的资源导致其效率低下。

安装软件包

有两种方法可以从 PyPI 安装软件包。您可以下载该软件包,然后运行 ​​python setup.py install。但现代的方法是使用 pip、setuptools 和wheel。

从 Python 3.4 和 Python 2.79 开始默认包含 Pip 和 setuptools,但您需要升级到最新版本:

  • Linux/macOS:pip install -U pip setuptools
  • Windows:python -m pip install -U pip setuptools
但是,不再支持 Python 2,因此您应该已经使用 Python 3.0 或更高版本来提高性能。

使用pip安装wheel:

pip install wheel.
Copy after login

要使用 pip 安装软件包,请发出此命令。

pip install <package_name>
Copy after login

其中 package_name 是包的名称。例如,要安装 Ansible,命令如下所示:

pip install ansible
Copy after login

如果需要特定版本,也可以指定如下:

pip install ansible==7.0
Copy after login

Python 包始终安装到环境中。我在这里不会介绍的一种常见做法是使用虚拟环境来管理具有不同解释器和/或不同安装包集的多个独立的 Python 安装。您可以在此处阅读有关虚拟环境的更多信息。

最佳实践

Python 打包权威提供了大量有关打包最佳实践的指导。这很重要,因为这是一个正在积极开发的领域,并且建议会快速发展。

此外,如果您想做一些特别的事情,例如从替代存储库而不是 PyPI 安装软件包或以更复杂的方式使用 pip,您会发现精彩的讨论和实用的建议。

结论

当您是 Python 初学者时,您会学习核心语言并享受使用它的乐趣。很快您就会发现标准库,并且随着您获得更多经验,您会从它的丰富性中受益越来越多。

作为 Pythonista,您发展的下一阶段是将 Python 社区在 PyPI 上带来的巨大优势融入到您的系统中。包作为可重用 Python 代码的部署单元使这个生态系统得以实现。

The above is the detailed content of Explore the use of Python 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)

Hot Topics

Java Tutorial
1660
14
PHP Tutorial
1260
29
C# Tutorial
1233
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 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 and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles