Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to encapsulate the Python code package

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "how to encapsulate Python code package". In daily operation, I believe many people have doubts about how to package Python code package. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to package Python code package". Next, please follow the editor to study!

Step 1: naming

The first is naming. Good names are usually short, easy to type after the pip install or import is complete (although "automatic typing" now appears), and also contain enough information to make it easier to understand, or prompt for its contents after installation.

Requests is responsible for processing HTTP requests, delorean is responsible for date and time, and sklearn is responsible for providing a machine learning framework. These are good examples.

But to be honest, these are not rules to be adhered to. Popular Python packages have names such as pandas, keras, django, boto, jinja, flask, and pytorch, which you can remember, so readers can also use any short and readable name (for example, the author abbreviated "Scikit-Learn Wrappers for FastText" to skift because of readability problems). This paper takes chocobo as an example.

Step 2: determine the basic structure of the code package

Next, create a general structure in a few short steps:

1. Create a Github repository with the exact name of the code package, do not use humps or too much personal play. Then replicate locally.

two。 Create a new folder in the repository and name it with the exact name of the code package; this is the folder where the code package is saved. This is a specification, just remember that the external chocobo folder (in this case) is the repository folder, while the internal chocobo folder is the package folder.

3. Put your own modules and any other modules involved in the internal chocobo folder. If there is a missing part, add the _ _ init__.py file.

4. Import important objects (usually functions) that the user calls directly from their respective modules into the _ _ init__.py file. With the namespace of the code package, you can use these functions, categories, and variables. You can also use the API of the code package if you prefer.

5. Although it is not mandatory, the author strongly recommends that you include a .gitignore file in either the code package or in the root directory of the repository.

Now you have a structure where you can add different types of files to form a code package; the internal folder holds the package code, and the external folder holds auxiliary package files and other repository-related files.

Therefore, the initial module chocobo.py looks like this:

"My chocobo cooking script." Import os def chocobo_roast (num_guests, hotness_level): # amazing python code here

The new repository folder is as follows:

Chocobo/ chocobo/ _ _ init__.py chocobo.py .gitignore

The _ _ init__.py file should look like this:

"chocobo is a python package for delicious Chocobo recipes." From .chocobo import (chocobo_roast,)

Then after the encapsulation is completed, the chocobo package can be used as follows:

"I'm a script or a different package using chocobo." Import chococbo def my_feast (num_guests): snacks = bobbish () main_course = chocobo.chocobo_roast (num_guests, 0) dressing = szechuan_chicken_mcnugget_sauce ()

These are some of the main points.

Step 3: licensing issues

It is preferable to distribute code under a shared license; if you want to share your code publicly, programmers will want permission to reuse the code without reserving copyright. or let those who extend their own code ensure that the derived code can be used freely. Getting permission may easily solve these problems.

Choosealicense.com (https://choosealicense.com/) provides a lot of practical advice from GitHub and the open source community.

Whichever license you choose is better than not having it at all. In many cases, it is better to disclose the code without permission; if programmers are not clear about their ownership of the code, most companies will give up because of possible legal disputes, thus losing many potential users.

After you select a license, create an LICENSE license file in the repository (no file extension is required) and import the exact text of the selected license.

Step 4: install the files

Now create the basic files needed for the Python wrapper tool (take setuptools as an example); setup.py.setup.py contains the actual instructions used during build and release.

Here is an initial template (don't worry, it will be checked in detail later)

"Setup for the chocobo package." Import setuptools with open ('README.md') as f: README = f.read () setuptools.setup (author= "Shay Palachy", author_email= "shay.palachy@gmail.com", name='chocobo', license= "MIT", description='chocobo is a python package for delicious chocobo recipes.', version='v0.0.3', long_description=README, url=' https://github.com/shaypal5/chocobo', packages=setuptools.find_packages (), python_requires= "> = 3.5" Install_requires= ['requests'], classifiers= [# Trove classifiers # (https://pypi.python.org/pypi?%3Aaction=list_classifiers)' Development Status:: 4-Beta', 'License:: OSI Approved:: MIT License',' Programming Language:: Python', 'Programming Language:: Python:: 3.5mm,' Programming Language:: Python:: 3.6legs, 'Topic:: Software Development:: Libraries',' Topic:: Software Development:: Libraries:: Python Modules' 'Intended Audience:: Developers',],)

First, import setuptools. This is a very useful code package that makes it easy to distribute Python packages, and even if it is not included in the standard library (similar distutils is not comparable), it is still the standard released by Python packages today and should be kept in mind. This article uses only two functions in the setuptools package: setup and find_packagges.

After importing setuptools, you just need to read the contents of the README.md file into the global variable README before calling the setup () function.

Then simply call the setuptools.setup () function with the following variables:

Author: enter a name.

Author_email: enter the mailbox.

Name: the name of the code package, in this case "chocobo".

License: in this case, the string "MIT", or select a different license.

Description: a short introduction to the code package, limited to one line. For example: "the chocobo code package is a recipe for making delicious chocobo."

Version: a string that represents the current version of the package. The author will introduce a more concise approach in a later article, but for now, you only need to manually add a number when you want to release a new version. The usual practice is to precede the version number with the letter V, so v1 is the version string of the first version, but the author recommends that v0.0.1 be treated as the equivalent version string and use this format. The significance of this practice will be described in detail later.

Long_description: represents the content of the README. This section is a detailed description of the code package. This is the content of the page PyPI (example: https://pypi.org/project/pdpipe/).

Url: links to the home page of the code package. If the reader does not have a dedicated site, then the URL of the repository is a good choice.

Packages: once again mentioned setuptools! According to the command, this parameter gets an array of names of all the code packages to be generated and released / installed. Technically, you can use the name ["chocobo"] directly, but it's best to generalize it and use the setuptools function, which can handle more complex package and repository structures. There are two optional parameters that can be used as input data, where and exclude, but are ignored here. As a result, where can link to the directory where the installation files are located, including all subdirectories, which is generally sufficient.

Python_requires: if your computer supports all versions of Python, you don't have to worry about this parameter. If not, you should select an appropriate value. Technically speaking, the author does not approve of using an untested version, but we can make appropriate assumptions during the insurance period:

(1) if readers are using Python2, especially the Python2.7 version, they can draw the following two conclusions: (a) you are unique and excellent; and (b) your computer configuration only needs to support Python2.7, so you can use the character "> = 2.7" to edit this parameter. Besides, the times are progressing, so try Python3.

(2) if the reader is using Python3, then any version of Python is greater than or equal to the version used to develop the code package. And so on, if you are using Python3.5, you should set it to "> = 3.5".

Install_requires: here are the prerequisites for the use of all non-standard library code packages. For example, if chocobo requires requests and pytz to run, this parameter should be set to: ["requests", "pytz"].

Classifiers: along with thousands of other code packages, your code package will soon be PyPI online. To distinguish, the author can provide PyPI with a list of trove classifiers to classify each version, describing its purpose, supported systems, and development progress. Community members can then use these standardized classifiers to find items according to their own needs (although they are not sure who will do so).

It is recommended to start with the following:

Development Status:: 3-Alpha

"License:: OSI Approved:: MIT License"

"Programming Language:: Python"

"Programming Language:: Python:: 3.5"

"Programming Language:: Python:: 3.6"

"Programming Language:: Python:: 3.7"

"Topic:: Software Development:: Libraries"

"Topic:: Software Development:: Libraries:: Python Modules"

"Intended Audience:: Developers"

Step 5: establish the release document

The Python package is located in the distribution file, which is uploaded to a single server (usually a PyPI global server) for public download.

First, make sure that the latest version of setuptools and wheel are installed:

Python3-m pip install-user-upgrade setuptools wheel

To build the release file, simply run the following command in the root directory of the repository where setup.py resides:

Python setup.py sdist bdist_wheel

In this step, you need Python to run the setup.py script and send it two parameters, generate the source file (parameter sdist), and the wheel tool to build the release file (parameter bdist_wheel).

When you run this command, three folders are created in the invocation directory: build, dist, and chocobo.egg-info. For .gitignore files, these three are negligible. If these directories already exist (for example, the command has been run before, it is best to delete them with rm-rf build dist, because any valid code package files under dist will be uploaded.

The two files to be uploaded are located in the dist folder: chocobo-0.0.3-py-none.any.whl (build release; a wheel file) and chocobo-0.0.3.tar.gz (source distribution; a compressed tar file). After the creation is successful, we will continue with the upload steps!

Step 6: upload

The remaining step is to upload the code package to the PyPI global server! However, users must first register on the PyPI website. Follow the registration steps to fill in the user name and password.

Programmers can also register a user on the test PyPI site if they want to test the package before uploading to the PyPI global server.

Now the Python package used for upload will look for the PyPI user name and password (verified by the PyPI server) in the .pypirc text file, which is usually located in the home folder. After creation, fill in as follows (the testpypi section depends on the situation):

[distutils] index-servers = pypi testpypi [pypi] username: teapot48 password: myPYPIpassword [testpypi] repository: https://test.pypi.org/legacy/ username: teapot48 password: MYtestPYPIpassword

This article follows the latest method of uploading files to a PyPI server and uses twine (a utility for uploading Python packages) instead of using outdated python setup.py upload. Just run:

Twine upload dist/*

If you want to test on a PyPI server, just run twine upload-repository testpypi dist/*

In any case, you should see a progress bar when uploading a .whl file and a progress bar when uploading a .tar.gz document, and then the upload is complete.

Now you can see your Python package page on the PyPI official website, and everyone can see it!

=

At this point, the study on "how to encapsulate the Python code package" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report