Labs / Board Reviews & Technical Insights

Publishing MicroPython/Python third-party libraries

Author: Li Zisheng · Source: FreakStudio open documentation · License: CC BY 4.0

Contents

Summary

This article covers the description and organization of the files in a third-party library, choosing an open-source license, automatic code formatting and static checking with the black module, the Flake8 module and a pre-commit hook, public release on GitHub/PyPI, and one-command installation of MicroPython third-party libraries with the mpremote tool.

0. Background

Recently, while using Hiwonder's serial bus servo library, I found some problems in its accompanying MicroPython SDK:

In fact, it neither decouples functionality well nor makes full use of Python's object-oriented features.

You can see that several methods contain duplicated send/receive logic:

At the same time, the UART baud rate (115200), timeout (50ms) and so on are hard-coded rather than configurable:

Moreover, there is no API documentation or example code, which makes it hard for users to get started quickly, and there is no input parameter validation, such as checking whether the servo ID, angle range and speed range are reasonable:

So I decided to write my own MicroPython version of the Hiwonder serial bus servo library.

Main features include:

- Communicates with the servos over a UART serial port and supports controlling multiple servos.

- Supports a variety of servo settings such as angle, speed and operating mode.

- Supports real-time reading of servo temperature, voltage, angle and more.

- A checksum mechanism ensures the integrity of data transmission, Hiwonder serial

- All 28 servo commands are implemented and wrapped in a class.

- Complete exception handling, with detailed checks on input parameters.

- Thorough comments; all methods and classes have type annotations.

The code is at: https://github.com/leezisheng/freakstudio-micropython-libraries/tree/main/serial_servo

By setting up its project dependency file, it can be downloaded with one command using the mpremote tool:


mpremote mip install github:leezisheng/freakstudio-micropython-libraries/serial_servo

For a detailed introduction, see my blog:

https://www.cnblogs.com/FreakEmbedded/p/18742422

While publishing the library, I found that many tutorials online are outdated and much of what they describe no longer works with current versions, and there are very few Chinese tutorials on publishing MicroPython third-party libraries, which is what prompted me to write this tutorial.

1. Introduction

Publishing MicroPython/Python third-party libraries figure 1

In the early days of the MicroPython ecosystem, developers who shared or used third-party libraries often had to download several files by hand and copy them into the project directory. This "copy and paste" approach was not only tedious but also easily led to version confusion, missing dependencies and similar problems. We can also see that a lot of code has incomplete documentation and comments, making it hard to use at first; you often look at an API and have no idea what type its input parameters are, as shown below:

As MicroPython community tools have matured (such as mpremote and upip), publishing third-party libraries following a standard process has become an essential part of learning MicroPython development. By writing a proper package.json project dependency file, a complete README.md file and code that follows PEP8, we can make the MicroPython libraries we write easier for others to use.

For example, we can use the mpremote tool to download a third-party module we wrote, together with its dependencies, with one command:

As you can see, a properly structured library means users do not have to manage file paths manually; dependency resolution and updates are handled automatically by the toolchain, which greatly lowers the barrier to use. And if the library is updated in our GitHub repository, it can still be installed with a single command.

Using the MicroPython serial bus servo library we wrote as an example, this article explains how to publish a MicroPython third-party library properly.

The code link is:

https://github.com/leezisheng/freakstudio-micropython-libraries/tree/main/serial_servo

Because publishing to MicroPython-lib is rather cumbersome, we published the whole library on PyPI:

https://pypi.org/project/serial-servo/

If you want to learn how to publish Python third-party libraries, this article is also a good fit for you.

This article is intended for beginners who have some Python background, understand Python virtual environment setup and object-oriented syntax, have done actual MicroPython development and have some awareness of version control, but are unfamiliar with open-source publishing. Its main contents include:

2. MicroPython third-party library files and folder organization

2.1 What publishing a library means

In MicroPython, publishing a library means sharing a finished functional module or utility library with other developers in a standardized way. By publishing the libraries we write, others can quickly integrate and use them without writing the same functionality from scratch. A published library usually contains the implementation, configuration files, example code and documentation, organized according to certain conventions, so that other users can use these modules through a simple install-and-import process.

For MicroPython, a published library is not just an ordinary .py file; it should also include project metadata, documentation, examples, a license and so on, so that other developers can quickly understand and use it. Below is how our serial bus servo library is organized:

As you can see, it includes the implementation files (.py files), a README.md file, an open-source license, an example main program, a project dependency file and so on.

A side note here: publishing a MicroPython library publicly on GitHub does not mean formally "publishing" it to a package management platform (such as PyPI), but the process is commonly called "publishing" or "public release", because you open your library to other developers and can use GitHub for version control, issue tracking and community collaboration.

Publishing a MicroPython library involves:

In general, MicroPython/Python libraries are published to the following platforms:

The differences are as follows:

PyPI

MicroPython-lib

GitHub/GitLab

Characteristics

  • PyPI is the most mainstream package management platform in the Python ecosystem and supports installation with pip.
  • Libraries published to PyPI are easily accessible to Python developers worldwide.
  • MicroPython libraries that depend on specific hardware features (such as GPIO, I2C, etc.) may not run directly from PyPI.
  • MicroPython officially maintains a library index (MicroPython Libraries) containing a large number of libraries optimized for MicroPython.
  • These libraries are usually reviewed by the MicroPython core team and have good compatibility and performance.
  • Suitable for publishing libraries that interact with hardware and use few resources.
  • The publishing process requires submitting a Pull Request on GitHub and passing community review.
  • GitHub/GitLab are the most commonly used code hosting platforms in the open-source community and support version control and collaborative development.
  • Libraries can be distributed via git clone or by downloading the source directly.
  • Suitable for publishing experimental or immature libraries, or libraries that need frequent updates.
  • Users have to download and install manually, which is less convenient than PyPI or the official MicroPython library index, but if the library's configuration and dependency file is written correctly and follows the package structure required by mpremote.

Intended for

  • Pure Python libraries
  • MicroPython-compatible libraries

MicroPython libraries

  • Pure Python libraries
  • MicroPython libraries

How the library is installed

Via pip install or conda install.

Via mpremote, downloading from GitHub, or copying to the device manually.

All of the above are supported

Here, to cover publishing third-party libraries for both Python and MicroPython, we choose PyPI as the publishing platform. Note, however, that we cannot install MicroPython libraries with pip, and this serial bus servo library cannot be used with Python on a PC either.

Because publishing on the MicroPython-lib platform is fairly tedious (for example, it requires test files written with the unittest framework), we will not cover it here. Interested readers can study the following after finishing this article:

micropython-lib/CONTRIBUTING.md at 65a14116d503dd544cbba92284517c99e5e9a448 · micropython/micropytho

2.2 Library organization

The folder structure of a Python/MicroPython third-party library is as follows:

my_micropython_library/
│
├── my_module.py               # Main module or functionality file of the library
├── __init__.py                # Optional; marks this as a package
├── README.md                  # Project documentation describing the library's purpose, installation, examples, etc.
├── LICENSE                    # Open-source license file declaring the terms of use
├── requirements.txt           # Optional; lists other libraries it depends on
├── examples/                  # Folder for example code
│   ├── example1.py
│   └── example2.py
└── library.properties         # Optional; the library's metadata file

This includes:

Here you can see how our library folder is organized:

The serial_servo folder is the library's root folder, and the serial_servo folder inside it contains the library's main implementation, including the __init__.py file and the serial_servo.py file:

For project dependency files, we use two kinds of files:

  1. package.json file: This file is usually used to describe the project's dependencies and metadata; it is used in MicroPython.
  2. requirements.txt and setup.py files: List the third-party libraries a Python project depends on; used in Python.

Here, if you only need to publish a MicroPython third-party library in your own GitHub repository, the package.json file alone is enough; if you need to publish a Python third-party library on PyPI, you need the requirements.txt and setup.py files; if you want to publish to the MicroPython-lib platform, you need to use manifest.py as the project dependency file.

2.3 Library files explained

2.3.1 Library implementation code

2.3.1.1 Core implementation file

Here, we need to create a subfolder with the same name inside the library's root folder and put the library's main implementation code in that subfolder. Taking our library as an example, the serial_servo folder is the library's root folder, and the serial_servo folder inside it contains the library's main implementation, including the __init__.py file and the serial_servo.py file:

Here, the serial_servo.py file is the library's core implementation file:

The third-party library we provide should organize related functionality in a class, which makes it easier to manage and extend. A class can encapsulate internal state (such as hardware configuration and sensor data) to avoid overusing global variables. For object-oriented programming in Python, see our earlier tutorial:

Possibly the most beginner-friendly object-oriented programming tutorial on the web: Python implementation - a must-read for embedded enthusiasts! - FreakStudio - cnblogs

When wrapping functionality in a class, pay attention to the following: clear function names, comments and docstrings, error handling and type annotations.

We need to make sure each method's name matches what it does. For example, move_servo_immediate clearly means moving the servo immediately, and calculate_checksum clearly expresses calculating a checksum. Example code:

    def calculate_checksum(self, data: list[int]) -> int:
        """
        Calculate the checksum.

        The checksum is obtained by summing the data packet and taking the one's complement (low eight bits of data), ensuring data integrity and correctness.

        Args:
            data (list[int]): Data packet (excluding the checksum itself).

        Returns:
            int: The calculated checksum, value range 0~255.

        ===================================================

        Calculate checksum to ensure data integrity and correctness.

        The checksum is obtained by summing the data packet and taking the one's complement (low eight bits of data).
        Args:
            data (list[int]): Data packet (excluding checksum itself).

        Returns:
            int: Calculated checksum, value range 0~255.

        """

        checksum = ~(sum(data) & 0xFF) & 0xFF

        return checksum

And you can see that above every function and method we add a detailed docstring explaining the purpose of each method, its input parameters and its return value.

Likewise, we use type annotations in the code to specify the types of variables, function parameters and return values, which helps other developers easily understand a function's input and output types:

    def build_packet(self, servo_id: int, cmd: int, params: list[int]) -> bytearray:
        return bytearray(packet)

    def send_command(self, servo_id: int, cmd: int, params: list[int] = []) -> None:
        self.uart.write(packet)

    def receive_command(self, expected_cmd: int, expected_data_len: int) -> list:
        return params

At the same time, pay attention to using appropriate error handling in methods. For example, the build_packet method checks whether servo_id is within the valid range and raises an exception if it is not:

    def build_packet(self, servo_id: int, cmd: int, params: list[int]) -> bytearray:
        """
        Build a servo command packet.

        Generate a complete data packet from the servo ID, command and parameters, and append the checksum.

        Args:
            servo_id (int): Servo ID, range 0~253, where 254 is the broadcast ID, meaning all servos.
            cmd (int): Command byte.
            params (list[int]): Parameter list.

        Returns:
            bytearray: The built servo control command packet.

        Raises:
            ValueError: Raised if the servo ID is not within the range 0~254.

        ===================================================

        Build servo control command packet, including checksum.

        Args:
            servo_id (int): Servo ID, range 0~253, where 254 is broadcast ID, indicating all servos.
            cmd (int): Command byte.
            params (list[int]): Parameter list (default empty).

        Returns:
            bytearray: Built servo control command packet, including checksum.

        Raises:
            ValueError: If the servo ID is not in the range 0~254, an exception will be raised.
        """
        # Check the input parameters
        # Check whether the servo ID is within 0~254
        if servo_id < 0 or servo_id > 254:
            raise ValueError("Servo ID must be in range 0~254.")

        # Packet length (command + parameters + checksum)
        length = 3 + len(params)
        # Build the packet: header + ID + data length + command + parameters + checksum
        packet = [0x55, 0x55, servo_id, length, cmd] + params
        # Calculate the checksum (from the ID to the last parameter)
        checksum = self.calculate_checksum(packet[2:])
        # Append the checksum
        packet.append(checksum)

        return bytearray(packet)

For more on error handling and type annotations, see the following two linked documents:

Related article on the Freak Embedded WeChat account (in Chinese)

Related article on the Freak Embedded WeChat account (in Chinese)

In the class docstring, we should also explain the class's overall role, functionality and usage:

# Custom serial bus servo class
class SerialServo:
    """
    Serial bus servo control class, used to generate and send control commands.

    This class communicates with the servos over a UART serial port and supports building control command packets, calculating checksums and sending commands.
    Supports an adjustable baud rate and control of different servos.

    Attributes:
        uart (machine.UART): UART instance used to communicate with the servos.

    Class Variables:
        - Definitions of the commands and their parameter lengths or return data lengths.
        - Definitions of the various servo control commands, including write commands and read commands.
        - Definitions of the servo operating modes.
        - Definitions of the LED alarm fault types.

    Methods:
        calculate_checksum(data: list[int]) -> int:
            Calculate the checksum to ensure data integrity and correctness.
        build_packet(servo_id: int, cmd: int, params: list[int]) -> bytearray:
            Build a servo command packet.
        send_command(servo_id: int, cmd: int, params: list[int] = []) -> None:
            Send a control command to the servo.
        receive_command(expected_cmd: int, expected_data_len: int) -> list:
            Receive and process the command data packet returned by the servo.
        move_servo_immediate(servo_id: int, angle: float, time_ms: int) -> None:
            Immediately move the servo to the specified angle.
        get_servo_move_immediate(servo_id: int) -> tuple:
            Get the servo's preset angle and time.

2.3.1.2 The __init__.py marker file

The __init.py__ file is a special Python file used to mark a directory as a Python package. If our module has several files, we can place an __init.py__ file in the same directory as the module files to mark the folder as a package, so that all Python files in that directory are treated as part of one package and can be imported and used with import statements.

For example, if the package contains several modules (such as module1.py, module2.py), the init.py file can import these modules with import statements, so that users can access the modules in the package directly through the package name:

from mypackage import module1

And if you want to provide certain interfaces or attributes at the package level, you can define them in the __init.py__ file:

# mypackage/__init__.py
from .module1 import MyClass

This way, users can access the MyClass class in module1.py directly with from mypackage import MyClass.

In the __init.py__ file of our serial bus servo class:

# Import the SerialServo class and expose it to package users
from .serial_servo import SerialServo

# Use __all__ to make sure only the SerialServo class is exposed
__all__ = ["SerialServo"]
# Define the version number
__version__ = "1.0.0"

We provide the SerialServo class at the package level and also define a simple version number.

For the basics of modules and packages in Python, see the following document:

Related article on the Freak Embedded WeChat account (in Chinese)

2.3.2 README file

In any open-source library, the README.md file is a very important file. It not only provides a basic introduction to the project but also helps other developers quickly understand how to use, contribute to and install the library; the README.md file can be said to be the project's "front door".

The README.md file is a text file, usually written in Markdown, and contains the following:

Project name: briefly states the project's name.
Project overview: explains the project's purpose, functionality or use cases and provides some background to help users understand what the project is for.
Installation guide: provides the steps to install and configure the project, including system requirements, dependencies and installation commands.
Usage: provides the basic steps to use the project, example code for the command line or API, sample configuration files, etc.
Features: lists the project's main functions and features so users understand what it can do.
Contributing guide: if the project is open source, explains how to contribute code, submit bug reports or give feedback.
License: states the type of license the project uses (such as MIT, GPL, etc.).
Development and testing: explains how to develop locally, test the project and submit changes.
Documentation links: if the project has more detailed documentation or external resources, provides these links.
Example code: provides basic usage examples or code snippets to help users get started quickly.
Contact: how users can contact the developer or team if they have questions or suggestions.
Acknowledgements: thanks contributors who helped the project or other open-source projects it depends on.

Our README file includes the following:

For details, see:

freakstudio-micropython-libraries/serial_servo/README.md at main · leezisheng/freakstudio-micropytho

We usually write README.md files with the Markdown plugin in PyCharm. Before writing an md file, you need to know some simple Markdown syntax; we recommend the following tutorial:

Learn Markdown step by step [from beginner to expert, this one article is all you need] - CSDN Blog

2.3.3 Open-source license

A license is similar to a legal agreement and is very important for any open-source project. It clearly specifies the permissions and restrictions on using, modifying and distributing a software project:

Publishing MicroPython/Python third-party libraries figure 2

There are many licenses, each with a different emphasis depending on the degree of freedom of use, whether commercial use is allowed, the requirements for modification and distribution, and privacy protection and legal liability. For example, some licenses (such as AGPL) focus on protecting user privacy, especially in network applications, by requiring modified code to be made public as well, preventing developers from using the software to collect user data while keeping it private.

Below is a widely circulated license selection chart (shared by an expert on Zhihu):

Here are three commonly used licenses:

Here we use the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) license, stated in the README.md file; you can see our LICENSE:

Creative Commons Attribution-NonCommercial 4.0 International License

Copyright 2025 Lee Qingshui / Freak

This work is licensed under the Creative Commons Attribution-NonCommercial 4.0 International License. 
You may not use the material for commercial purposes. 
You must give appropriate credit, provide a link to the license, and indicate if changes were made. 
You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.

To view a copy of this license, visit:
https://creativecommons.org/licenses/by-nc/4.0/

2.3.4 Project dependency and installation configuration files

2.3.4.1 Python

In pure Python, we use a requirements.txt file and a setup.py file to describe the published library's dependencies and their versions, the project metadata, and how to install and distribute the project:

requirements.txt is a common configuration file that lists all the Python packages the project depends on and their version requirements:

setuptools~=70.0.0
machine
time

Above is our requirements.txt; you can see each line lists one dependency and specifies a version.

setup.py is the traditional installation configuration file for Python projects and is essential when we publish a package to the Python Package Index (PyPI). It provides project information (such as name, version, author) as well as dependencies and how to install it.

from setuptools import setup, find_packages

# Read the contents of the README file
with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

setup(
    name="serial_servo",
    version="1.0.5",
    description="A MicroPython library to control servo motors via UART",
    author="leeqingshui",
    url="https://github.com/leezisheng/freakstudio-micropython-libraries",
    packages=find_packages(where="serial_servo"),
    long_description=long_description,
    long_description_content_type="text/markdown",
    install_requires=[
        # Uses only MicroPython built-in modules
    ],
    classifiers=[
        "Programming Language :: Python :: 3",     # Supports Python 3
        "Programming Language :: Python :: 3.8",   # Supports Python 3.8
        "License :: Other/Proprietary License",    # Uses the CC BY-NC 4.0 license
        "Operating System :: OS Independent",      # OS independent
    ],
    # Python version requirement (to match MicroPython; the Python version supported by v1.23.0)
    python_requires='>=3.12',
    # MicroPython-related dependencies, if any, can be added here
    extras_require={
        # MicroPython dependencies
        'micropython': ['machine', 'time'],
    },
)

In the setup.py file, setup is a function from the setuptools library. Its arguments form a dictionary containing the project's various metadata and configuration items, that is, the project's basic information, the minimum required Python version and specific dependencies. Common parameters are:

2.3.4.2 MicroPython

For MicroPython, we use a package.json or manifest.py file to describe the published library's dependencies and their versions, the project metadata, and how to install and distribute the project.

For how to write the package.json file, we can refer to the MicroPython documentation:

Package management ¶

The package.json file is a JSON-format configuration file used mainly in MicroPython projects to define and manage a library's dependencies, version, installation sources and other information. It describes how library files are uploaded and installed onto the device, and MicroPython uses it to handle library installation and dependency management.

Below is the package.json file of our serial bus servo driver library:

{
  "name": "serial_servo",
  "version": "1.0.5",
  "description": "A MicroPython library to control servo motors via UART",
  "author": "leeqingshui",
  "url": "https://github.com/leezisheng/freakstudio-micropython-libraries",
  "urls": [
    ["serial_servo/__init__.py", "github:leezisheng/freakstudio-micropython-libraries/serial_servo/serial_servo/__init__.py"],
    ["serial_servo/serial_servo.py", "github:leezisheng/freakstudio-micropython-libraries/serial_servo/serial_servo/serial_servo.py"]
  ],
  "deps": [
    ["micropython-machine", "latest"],
    ["micropython-time", "latest"]
  ],
  "version": "1.0.5",
  "long_description": "A MicroPython library to control servo motors via UART",
  "long_description_content_type": "text/markdown",
  "classifiers": [
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.8",
    "License :: Other/Proprietary License",
    "Operating System :: OS Independent"
  ],
  "python_requires": ">=3.12",
  "extras_require": {
    "micropython": ["machine", "time"]
  }
}

Its basic information is:

The other three main parameters are:

When the package.json file is written correctly, we can use the mip and mpremote tools to download a third-party library published on GitHub into the corresponding folder on the MCU with a single command; package.json is suited to simple static configuration.

You may also see some MicroPython libraries elsewhere that use manifest.py as the project dependency file, for example the MQTT library we use often:

micropython-lib/micropython/umqtt.robust/manifest.py at master · micropython/micropython-lib

Publishing MicroPython/Python third-party libraries figure 3

Unlike the package.json file, manifest.py is a Python script. Its role is similar to that of the package.json file: both describe the library's metadata, dependencies and how to integrate the library into MicroPython firmware. It is usually used for libraries published to micropython-lib, and is implemented mainly through the built-in metadata function:

def metadata():
    return {
        "name": "mlx90640",
        "version": "0.2",
        "description": "Library for controlling the mlx90640 sensor",
        "dependencies": [
            ("collections-defaultdict", "latest"),
            ("os-path", "latest")
        ]
    }

The fields mean:

The manifest.py file is suited to more complex configuration and dynamic logic, for example choosing different dependencies depending on the platform:

def metadata():
    dependencies = {
        "collections-defaultdict": "latest",
        "os-path": "latest"
    }

    # Add platform-specific dependencies
    import sys
    if sys.platform == "esp32":
        dependencies["esp32-specific-lib"] = "latest"
    elif sys.platform == "rp2":
        dependencies["rp2-specific-lib"] = "latest"

    return {
        "description": "A library with platform-specific dependencies.",
        "version": "0.1",
        "dependencies": dependencies
    }

In this scenario, manifest.py can adjust dependencies dynamically according to the platform it runs on, which package.json cannot do. manifest.py can also generate the file list dynamically, and can even include or exclude certain files based on conditions:

def metadata():
    files = [
        ("mylibrary/__init__.py", "github:org/mylibrary/mylibrary/__init__.py"),
        ("mylibrary/core.py", "github:org/mylibrary/mylibrary/core.py")
    ]

    # Add extra files depending on configuration
    import os
    if os.getenv("USE_ADVANCED_FEATURES") == "1":
        files.append(("mylibrary/advanced.py", "github:org/mylibrary/mylibrary/advanced.py"))

    return {
        "description": "A library with optional advanced features.",
        "version": "0.1",
        "files": files
    }

It can also include features such as debug logging and error handling:

import logging

logging.basicConfig(level=logging.DEBUG)

def metadata():
    logging.debug("Generating metadata for the library")
    return {
        "name": "library-with-debug",
        "version": "1.0",
        "description": "Library with dynamic configuration",
        "dependencies": [("os-path", "latest")]
    }

For JSON format, see our earlier tutorial:

Related article on the Freak Embedded WeChat account (in Chinese)

2.3.5 Example files

Here we did not include separate example files; usage examples are given in the README.md file:

from machine import Pin, UART
from serial_servo import SerialServo

# Configure the UART serial port
uart = UART(1, baudrate=115200, tx=Pin(4), rx=Pin(5))

# Initialize the serial bus servo control class
servo = SerialServo(uart)

# Move the servo to the specified angle
servo.move_servo_immediate(servo_id=1, angle=90.0, time_ms=1000)

# Get the servo's angle and time settings
angle, time = servo.get_servo_move_immediate(servo_id=1)
print(f"Servo ID: 1, Angle: {angle}, Time: {time}")

2.3.6 Other files

Here we have no other files, only the images referenced in the README.md file, which we put in the image folder:

In practice, we could set up a separate extra folder for reference files and images.

3. Code formatting and static checking

When publishing a MicroPython third-party module, code formatting and static checking are very important steps. We want each of our libraries to have similar indentation, line width and style, rather than being a mess:

When writing code, we usually follow the PEP8 code style. PEP8 is Python's official coding style guide and defines the formatting conventions for Python code:

Publishing MicroPython/Python third-party libraries figure 4

The purpose of PEP8 is to improve code readability and maintainability through a consistent code style. Following these conventions makes Python code more Pythonic.

For more information on PEP8, see the article at the following link:

Related article on the Freak Embedded WeChat account (in Chinese)

3.1 Formatting code with the black module

Publishing MicroPython/Python third-party libraries figure 5

black is an automated Python code formatter. It automatically formats code according to PEP8 so that it meets a uniform style. The benefit of using black is that it corrects code formatting automatically, with no manual adjustment needed.

Its formatting style looks like the code below:

First, open a terminal in the directory of the code to be formatted, activate the virtual environment, and install black:

pip install black

After installation, you can format code with the following command:

black <path-to-your-python-files>

Here we format the serial_servo.py file in the directory:

Compare before and after in GitHub Desktop:

You can see that the comments, indentation and line lengths have all changed and the layout is done.

3.2 Static code checking with the Flake8 module

Flake8 is a static checking tool for Python code. It analyzes code and checks whether it complies with PEP8 and other style guides. Its main purpose is to help developers keep a consistent code style, catch common errors and improve code quality.

Publishing MicroPython/Python third-party libraries figure 6

Flake8 mainly offers the following features:

pip install flake8

After installation, you can use flake8 on the command line to check Python files:

flake8 <your_python_file>.py

It outputs the following:

(MicroPython_Learn) PS G:\test> flake8 .\serial_servo.py
.\serial_servo.py:8:80: E501 line too long (91 > 79 characters)
.\serial_servo.py:16:80: E501 line too long (92 > 79 characters)
.\serial_servo.py:18:80: E501 line too long (92 > 79 characters)
.\serial_servo.py:20:80: E501 line too long (92 > 79 characters)
.\serial_servo.py:49:80: E501 line too long (80 > 79 characters)
.\serial_servo.py:53:80: E501 line too long (86 > 79 characters)
.\serial_servo.py:65:80: E501 line too long (98 > 79 characters)
.\serial_servo.py:69:80: E501 line too long (89 > 79 characters)
.\serial_servo.py:73:80: E501 line too long (83 > 79 characters)
.\serial_servo.py:107:80: E501 line too long (84 > 79 characters)
.\serial_servo.py:109:80: E501 line too long (119 > 79 characters)
.\serial_servo.py:118:80: E501 line too long (91 > 79 characters)
.\serial_servo.py:131:80: E501 line too long (80 > 79 characters)
.\serial_servo.py:135:80: E501 line too long (86 > 79 characters)
.\serial_servo.py:147:80: E501 line too long (98 > 79 characters)
.\serial_servo.py:151:80: E501 line too long (89 > 79 characters)
.\serial_servo.py:155:80: E501 line too long (83 > 79 characters)
.\serial_servo.py:307:80: E501 line too long (81 > 79 characters)
.\serial_servo.py:328:80: E501 line too long (117 > 79 characters)
.\serial_servo.py:341:80: E501 line too long (84 > 79 characters)
.\serial_servo.py:363:80: E501 line too long (100 > 79 characters)
.\serial_servo.py:371:80: E501 line too long (95 > 79 characters)
.\serial_servo.py:389:80: E501 line too long (84 > 79 characters)
.\serial_servo.py:413:80: E501 line too long (95 > 79 characters)
.\serial_servo.py:419:80: E501 line too long (81 > 79 characters)
.\serial_servo.py:440:80: E501 line too long (132 > 79 characters)
.\serial_servo.py:448:80: E501 line too long (116 > 79 characters)
.\serial_servo.py:451:80: E501 line too long (97 > 79 characters)
.\serial_servo.py:495:80: E501 line too long (86 > 79 characters)
.\serial_servo.py:515:80: E501 line too long (91 > 79 characters)
.\serial_servo.py:516:80: E501 line too long (133 > 79 characters)
.\serial_servo.py:519:80: E501 line too long (103 > 79 characters)
.\serial_servo.py:571:80: E501 line too long (127 > 79 characters)
.\serial_servo.py:578:80: E501 line too long (142 > 79 characters)
.\serial_servo.py:582:80: E501 line too long (108 > 79 characters)
.\serial_servo.py:593:80: E501 line too long (84 > 79 characters)
.\serial_servo.py:637:80: E501 line too long (108 > 79 characters)
.\serial_servo.py:642:80: E501 line too long (115 > 79 characters)
.\serial_servo.py:643:80: E501 line too long (135 > 79 characters)
.\serial_servo.py:646:80: E501 line too long (108 > 79 characters)
.\serial_servo.py:696:80: E501 line too long (92 > 79 characters)
.\serial_servo.py:698:80: E501 line too long (119 > 79 characters)
.\serial_servo.py:705:80: E501 line too long (142 > 79 characters)
.\serial_servo.py:709:80: E501 line too long (108 > 79 characters)
.\serial_servo.py:715:80: E501 line too long (100 > 79 characters)
.\serial_servo.py:719:80: E501 line too long (81 > 79 characters)
.\serial_servo.py:767:80: E501 line too long (129 > 79 characters)
.\serial_servo.py:768:80: E501 line too long (92 > 79 characters)
.\serial_servo.py:774:80: E501 line too long (97 > 79 characters)
.\serial_servo.py:795:80: E501 line too long (141 > 79 characters)
.\serial_servo.py:801:80: E501 line too long (97 > 79 characters)
.\serial_servo.py:822:80: E501 line too long (111 > 79 characters)
.\serial_servo.py:829:80: E501 line too long (112 > 79 characters)
.\serial_servo.py:858:80: E501 line too long (118 > 79 characters)
.\serial_servo.py:867:80: E501 line too long (97 > 79 characters)
.\serial_servo.py:912:80: E501 line too long (113 > 79 characters)
.\serial_servo.py:914:80: E501 line too long (106 > 79 characters)
.\serial_servo.py:919:80: E501 line too long (96 > 79 characters)
.\serial_servo.py:920:80: E501 line too long (120 > 79 characters)
.\serial_servo.py:923:80: E501 line too long (102 > 79 characters)
.\serial_servo.py:943:80: E501 line too long (84 > 79 characters)
.\serial_servo.py:970:80: E501 line too long (124 > 79 characters)
.\serial_servo.py:971:80: E501 line too long (132 > 79 characters)
.\serial_servo.py:977:80: E501 line too long (84 > 79 characters)
.\serial_servo.py:981:80: E501 line too long (109 > 79 characters)
.\serial_servo.py:1032:80: E501 line too long (94 > 79 characters)
.\serial_servo.py:1040:80: E501 line too long (119 > 79 characters)
.\serial_servo.py:1093:80: E501 line too long (123 > 79 characters)
.\serial_servo.py:1100:80: E501 line too long (111 > 79 characters)
.\serial_servo.py:1104:80: E501 line too long (120 > 79 characters)
.\serial_servo.py:1115:80: E501 line too long (88 > 79 characters)
.\serial_servo.py:1159:80: E501 line too long (102 > 79 characters)
.\serial_servo.py:1163:80: E501 line too long (95 > 79 characters)
.\serial_servo.py:1164:80: E501 line too long (95 > 79 characters)
.\serial_servo.py:1167:80: E501 line too long (125 > 79 characters)
.\serial_servo.py:1171:80: E501 line too long (82 > 79 characters)
.\serial_servo.py:1218:80: E501 line too long (123 > 79 characters)
.\serial_servo.py:1225:80: E501 line too long (94 > 79 characters)
.\serial_servo.py:1229:80: E501 line too long (125 > 79 characters)
.\serial_servo.py:1241:80: E501 line too long (84 > 79 characters)
.\serial_servo.py:1283:80: E501 line too long (82 > 79 characters)
.\serial_servo.py:1287:80: E501 line too long (97 > 79 characters)
.\serial_servo.py:1290:80: E501 line too long (119 > 79 characters)
.\serial_servo.py:1294:80: E501 line too long (87 > 79 characters)
.\serial_servo.py:1298:80: E501 line too long (87 > 79 characters)
.\serial_servo.py:1322:80: E501 line too long (142 > 79 characters)
.\serial_servo.py:1329:80: E501 line too long (122 > 79 characters)
.\serial_servo.py:1333:80: E501 line too long (119 > 79 characters)
.\serial_servo.py:1338:80: E501 line too long (81 > 79 characters)
.\serial_servo.py:1382:80: E501 line too long (131 > 79 characters)
.\serial_servo.py:1388:80: E501 line too long (80 > 79 characters)
.\serial_servo.py:1392:80: E501 line too long (112 > 79 characters)
.\serial_servo.py:1439:80: E501 line too long (123 > 79 characters)
.\serial_servo.py:1445:80: E501 line too long (99 > 79 characters)
.\serial_servo.py:1449:80: E501 line too long (109 > 79 characters)
.\serial_servo.py:1499:80: E501 line too long (124 > 79 characters)
.\serial_servo.py:1500:80: E501 line too long (103 > 79 characters)
.\serial_servo.py:1506:80: E501 line too long (95 > 79 characters)
.\serial_servo.py:1510:80: E501 line too long (103 > 79 characters)
.\serial_servo.py:1546:80: E501 line too long (85 > 79 characters)
.\serial_servo.py:1567:80: E501 line too long (96 > 79 characters)
.\serial_servo.py:1568:80: E501 line too long (127 > 79 characters)
.\serial_servo.py:1571:80: E501 line too long (124 > 79 characters)
.\serial_servo.py:1578:80: E501 line too long (92 > 79 characters)
.\serial_servo.py:1627:80: E501 line too long (127 > 79 characters)
.\serial_servo.py:1634:80: E501 line too long (127 > 79 characters)
.\serial_servo.py:1637:80: E501 line too long (119 > 79 characters)
.\serial_servo.py:1642:80: E501 line too long (80 > 79 characters)
.\serial_servo.py:1688:80: E501 line too long (125 > 79 characters)
.\serial_servo.py:1723:80: E501 line too long (123 > 79 characters)
.\serial_servo.py:1724:80: E501 line too long (88 > 79 characters)
.\serial_servo.py:1730:80: E501 line too long (131 > 79 characters)
.\serial_servo.py:1735:80: E501 line too long (81 > 79 characters)
.\serial_servo.py:1775:80: E501 line too long (117 > 79 characters)
.\serial_servo.py:1786:80: E501 line too long (85 > 79 characters)
.\serial_servo.py:1809:80: E501 line too long (102 > 79 characters)
.\serial_servo.py:1810:80: E501 line too long (83 > 79 characters)
.\serial_servo.py:1816:80: E501 line too long (99 > 79 characters)
.\serial_servo.py:1820:80: E501 line too long (108 > 79 characters)
.\serial_servo.py:1831:80: E501 line too long (82 > 79 characters)
.\serial_servo.py:1861:80: E501 line too long (100 > 79 characters)
.\serial_servo.py:1862:80: E501 line too long (97 > 79 characters)
.\serial_servo.py:1866:80: E501 line too long (112 > 79 characters)
.\serial_servo.py:1869:80: E501 line too long (89 > 79 characters)
.\serial_servo.py:1911:80: E501 line too long (111 > 79 characters)
.\serial_servo.py:1912:80: E501 line too long (108 > 79 characters)
.\serial_servo.py:1913:80: E501 line too long (85 > 79 characters)
.\serial_servo.py:1919:80: E501 line too long (101 > 79 characters)
.\serial_servo.py:1923:80: E501 line too long (110 > 79 characters)
.\serial_servo.py:1934:80: E501 line too long (84 > 79 characters)
.\serial_servo.py:1962:80: E501 line too long (91 > 79 characters)
.\serial_servo.py:1964:80: E501 line too long (92 > 79 characters)

First, let's go over the common Flake8 error codes. Flake8 uses a set of common error codes, usually made up of a letter and digits. For example:

The output above says the lines are too long:

In fact, we can change the maximum allowed line length. Flake8 supports managing and customizing rules through a configuration file. You can create a .flake8 file or configure it in the setup.cfg file.

[flake8] 
max-line-length = 150 
exclude = .git, __pycache__, build, dist 
ignore = E203, W503
Publishing MicroPython/Python third-party libraries figure 7

Here we set the line length limit to 150 characters (the default is 79), exclude the .git, pycache, build and dist directories from checking, and ignore the E203 and W503 errors.

Run it again: no errors.

3.3 Running automatically with a pre-commit hook

As you can see, when using the black and flake8 tools we have to type the commands manually every time, which is not only tedious but also easy to forget. In fact, we can use the Git hook mechanism to run the black and flake8 tools automatically every time code is committed.

Publishing MicroPython/Python third-party libraries figure 8
Publishing MicroPython/Python third-party libraries figure 9

Git hooks are a mechanism provided by Git that lets you automatically run custom scripts or programs before or after performing Git operations (such as commit, push, merge). With Git hooks, developers can insert custom actions at specific moments for automated processing, improving development efficiency and ensuring code quality and consistency. The name "hooks" in Git comes from what they do and how they work: in computer science, a "hook" usually refers to a mechanism that lets code be "hooked" into a system or process when a specific event occurs.Git hooks are essentially scripts (usually shell scripts). When you perform a specific Git operation (commit, push, merge), Git automatically triggers the corresponding hook so that a specific script runs automatically before or after the operation. It is like hanging a hook on an event, so that when the event occurs the hook can perform some actions.

Git hooks fall into two categories:

In addition, Git hook names follow certain rules, usually based on the name or behavior of the Git operation, with a specific prefix or suffix indicating when the hook runs. Below are the naming rules of some common Git hooks:

Here we use the pre-commit client-side Git hook, which runs before the git commit command executes. With pre-commit we can automatically call tools such as black and flake8 before a Git commit operation (such as git commit).

First, install the pre-commit module with the pip tool:

pip install pre-commit

Then create a configuration file named .pre-commit-config.yaml in the project root. This file contains the hooks you want to run when committing with Git.

Our configuration file contains the following:

repos:
  - repo: git@github.com:psf/black.git
    rev: 24.3.0
    hooks:
      - id: black
        args: [--line-length=150]

  - repo: git@github.com:pycqa/flake8.git
    rev: 7.0.0
    hooks:
      - id: flake8
        args: ["--ignore=E203,E501,W503", "--max-line-length=150"]

This .pre-commit-config.yaml configuration defines two Git hooks: one runs the black formatter with a maximum line length of 150 characters; the other runs the flake8 linting tool, ignoring the E203, E501 and W503 errors, with a maximum line length of 150 characters.

pre-commit also provides some other commonly used hook repositories, including mypy (a type checker for detecting type errors), isort (automatically sorts import statements), pytest (runs tests) and trailing-whitespace (removes trailing whitespace). All of these tools can be chosen according to the project's needs and configured in the .pre-commit-config.yaml file.

First, we use the following command to automatically update the .pre-commit-config.yaml file, updating the hook repositories defined in the .pre-commit-config.yaml file to their latest versions:

pre-commit autoupdate

Then run the following command to install the hooks specified in the .pre-commit-config.yaml configuration:

pre-commit install

This command creates a .git/hooks/pre-commit file that links the hook script to the Git repository. After that, Git triggers the hook every time git commit is run.

The next time we commit, black and flake8 run first, find anything non-compliant and can format it for you automatically; after you fix things and commit again, the commit goes through.

Let's add some errors to the source code:

Click commit:

Publishing MicroPython/Python third-party libraries figure 10

You can see the errors are detected:

As you can see, every time git commit is run, the pre-commit hook runs automatically and checks and formats the code before the commit. If the hook detects a problem in the code (for example non-compliant formatting or static check errors), it blocks the commit and reports the corresponding error messages. After deleting the erroneous line, commit again:

You can see the commit succeeds.

We can also choose to run the hooks manually without committing, using the following command:

pre-commit run --all-files

Let's give it a quick test:

3.4 Using a GitHub accelerator

Note that if repo in the .pre-commit-config.yaml configuration file points to an online repository on GitHub, you may run into access delays or failures when pulling or updating the repositories for the Git hooks, causing the commit operation to fail:

(MicroPython_Learn) PS G:\test> pre-commit run --all-files
[INFO] Initializing environment for git@github.com:psf/black.git.
origin', '--tags')
stdout: (none)
stderr:
    banner exchange: Connection to 20.205.243.166 port 22: Software caused connection abort
    fatal: Could not read from remote repository.

    Please make sure you have the correct access rights
    and the repository exists.
Check the log at C:\Users\Administrator\.cache\pre-commit\pre-commit.log

To avoid this, consider turning on a GitHub accelerator, or using a proxy service to speed up access to GitHub, so that the .pre-commit hooks run normally.

Here we use FastGithub.UI for acceleration:

Publishing MicroPython/Python third-party libraries figure 11

You can see that upload and download traffic during the commit operation is noticeably faster:

3.5 Introduction to the mpremote tool and one-command download

In fact, if you only want to publish a third-party library in your own GitHub repository, then after finishing functional testing of the code module and running code formatting and static checking, you can simply use the mpremote tool to download the code with one command. mpremote is an official command-line tool provided by MicroPython that can upload and download files, run scripts, manage devices and more. For details, see the following document:

MicroPython remote control: mpremote ¶

Here we only explain how to download library files with the mpremote tool. Taking our library as an example, the address is:

https://github.com/leezisheng/freakstudio-micropython-libraries/tree/main/serial_servo

Use the following command to download the library files with one command via the mpremote and mip tools:

mpremote mip install github:leezisheng/freakstudio-micropython-libraries/serial_servo

During installation it shows:

(base) PS D:\lee\windows terminal\terminal-1.17.11461.0> mpremote mip install github:leezisheng/freakstudio-micropython-libraries/serial_servo
Install github:leezisheng/freakstudio-micropython-libraries/serial_servo
Installing github:leezisheng/freakstudio-micropython-libraries/serial_servo/package.json to /lib
Installing: /lib/serial_servo/__init__.py
Installing: /lib/serial_servo/serial_servo.py
Installing micropython-machine (latest) from https://micropython.org/pi/v2 to /lib
Package may be partially installed
mpremote: Package not found: https://micropython.org/pi/v2/package/6/micropython-machine/latest.json

After installation, connect to your board with the mpremote tool. If the installation succeeded, it shows the following:

(base) PS D:\lee\windows terminal\terminal-1.17.11461.0> mpremote connect COM8
Connected to MicroPython at COM8
Use Ctrl-] or Ctrl-x to exit this shell

>>> import os
>>> os.listdir()
['lib']
>>> from serial_servo import SerialServo
>>>

4. Public release on PyPI

4.1 Registering on PyPI

We won't go into detail here; just follow the tutorial at the following link to register:

zhuanlan.zhihu.com

Note that PyPI requires Two-Factor Authentication (2FA) to be enabled to improve account security. After registering, go to the account settings page, select Add two-factor authentication, scan the QR code with an authenticator app and save the recovery codes.

We need to download the Microsoft Authenticator app on a phone in advance for 2FA login:

Publishing MicroPython/Python third-party libraries figure 12

After registering and enabling 2FA, go to the API token section under 2FA in the account settings and create a new API token:

Enter a token name and scope. If you have not uploaded a third-party library to PyPI before, just choose Entire account:

Copy this token and save it; we will need it every time we publish a library:

Publishing MicroPython/Python third-party libraries figure 13

4.2 Creating the distribution packages

Here we use setuptools and twine to create the distribution packages. When packaging with setuptools, the generated distribution packages are .tar.gz and .whl files, which you can see in the dist folder; the distribution packages we create are an archive file and a whl file:

twine is a tool for securely uploading Python packages to the Python Package Index (PyPI); it uses HTTPS and encrypted transfer. We install twine with pip:

pip install twine

Next, we use setuptools to create distribution packages in .tar.gz and .whl formats. Note that the terminal must be opened in the root directory of the library we want to publish:

python setup.py sdist bdist_wheel

The output is as follows:

(MicroPython_Learn) PS F:\freakstudio-micropython-libraries\serial_servo> python setup.py sdist bdist_wheel
running sdist
running egg_info
writing serial_servo.egg-info\PKG-INFO
writing dependency_links to serial_servo.egg-info\dependency_links.txt
writing requirements to serial_servo.egg-info\requires.txt
writing top-level names to serial_servo.egg-info\top_level.txt
reading manifest file 'serial_servo.egg-info\SOURCES.txt'
adding license file 'LICENSE'
writing manifest file 'serial_servo.egg-info\SOURCES.txt'
running check
creating serial_servo-1.0.5
creating serial_servo-1.0.5\serial_servo
creating serial_servo-1.0.5\serial_servo.egg-info
copying files to serial_servo-1.0.5...
copying LICENSE -> serial_servo-1.0.5
copying README.md -> serial_servo-1.0.5
copying setup.py -> serial_servo-1.0.5
copying serial_servo\__init__.py -> serial_servo-1.0.5\serial_servo
copying serial_servo\serial_servo.py -> serial_servo-1.0.5\serial_servo
copying serial_servo.egg-info\PKG-INFO -> serial_servo-1.0.5\serial_servo.egg-info
copying serial_servo.egg-info\SOURCES.txt -> serial_servo-1.0.5\serial_servo.egg-info
copying serial_servo.egg-info\dependency_links.txt -> serial_servo-1.0.5\serial_servo.egg-info
copying serial_servo.egg-info\requires.txt -> serial_servo-1.0.5\serial_servo.egg-info
copying serial_servo.egg-info\top_level.txt -> serial_servo-1.0.5\serial_servo.egg-info
copying serial_servo.egg-info\SOURCES.txt -> serial_servo-1.0.5\serial_servo.egg-info
Writing serial_servo-1.0.5\setup.cfg
Creating tar archive
removing 'serial_servo-1.0.5' (and everything under it)
running bdist_wheel
running build
G:\miniconda\setup\envs\MicroPython_Learn\Lib\site-packages\setuptools\_distutils\cmd.py:66: SetuptoolsDeprecationWarning: setup.py install is deprecated.
!!

        ********************************************************************************
        Please avoid running ``setup.py`` directly.
        Instead, use pypa/build, pypa/installer or other
        standards-based tools.

        See https://blog.ganssle.io/articles/2021/10/setup-py-deprecated.html for details.
        ********************************************************************************

!!
  self.initialize_options()
installing to build\bdist.win-amd64\wheel
running install
running install_egg_info
Copying serial_servo.egg-info to build\bdist.win-amd64\wheel\.\serial_servo-1.0.5-py3.12.egg-info
running install_scripts
creating build\bdist.win-amd64\wheel\serial_servo-1.0.5.dist-info\WHEEL
creating 'dist\serial_servo-1.0.5-py3-none-any.whl' and adding 'build\bdist.win-amd64\wheel' to it

You can see that the .tar.gz and .whl files have been created in the dist folder:

Next, use the following command to upload all packages in the dist/ folder:

twine upload dist/*

Enter the API token created earlier:

You can see it is uploading:

Because this version of the package had already been published, it shows that it cannot be published here. Normally, a URL for the third-party library is generated; opening it takes you to the library's page, similar to the following:

We can also choose to download the source files directly:

Note that when you publish a new version of the library, you need to manually delete the old version's packages from the dist/ folder.

After the upload is complete, we can install it with the pip tool (this library cannot run on a PC, so this is only a demonstration):

pip install serial-servo

It shows the following:

Open the installation location and you can see:

5. References

https://docs.micropython.org/en/latest/reference/packages.html#writing-publishing-packages

https://github.com/leezisheng/freakstudio-micropython-libraries/tree/main/serial_servo

https://github.com/micropython/micropython-lib/blob/master/.pre-commit-config.yaml

https://github.com/micropython/micropython-lib/blob/65a14116d503dd544cbba92284517c99e5e9a448/CONTRIBUTING.md

https://blog.csdn.net/wuShiJingZuo/article/details/135765628

https://www.ctyun.cn/developer/article/616592047181893

https://zhuanlan.zhihu.com/p/336238526

https://zhuanlan.zhihu.com/p/65820736

https://www.jianshu.com/p/eba337fe0828

https://www.runoob.com/w3cnote/open-source-license.html

https://zhuanlan.zhihu.com/p/682004873