114532 Views
101685 Views
86270 Views
54891 Views
51137 Views
49962 Views
Level Up your CAD Skills
Operation Pico
Raspberry Pi Home Hub
Hacky Temperature and Humidity Sensor
Robot Makers Almanac
High Five Bot
Using the Raspberry Pi Pico's Built-in Temperature Sensor
Getting Started with SQL
Introduction to the Linux Command Line on Raspberry Pi OS
How to install MicroPython
Wall Drawing Robot Tutorial
BrachioGraph Tutorial
KevsRobots Learning Platform
60% Percent Complete
By Kevin McAleer, 3 Minutes
In MicroPython, a package is a collection of modules that are organized in a directory structure. Packages help in organizing code and making it reusable. A package can contain sub-packages, modules, and other resources.
package
A package is a directory containing a special file named __init__.py. This file can be empty or contain initialization code for the package. The presence of the __init__.py file indicates to Python that the directory should be treated as a package.
__init__.py
Hereโs an example of a simple package structure:
my_package/ __init__.py module1.py module2.py sub_package/ __init__.py module3.py
In this example, my_package is a package that contains two modules (module1.py and module2.py) and a sub-package (sub_package) which itself contains an __init__.py file and a module (module3.py).
my_package
module1.py
module2.py
sub_package
module3.py
Create a directory for your package. Inside this directory, create an __init__.py file and the modules you need. For example, create the following structure:
my_robot_package/ __init__.py motors.py sensors.py
Add the following code to motors.py:
motors.py
# motors.py class Motor: def __init__(self, power): self.power = power def move(self, direction): print(f"Moving {direction} with power {self.power}")
And add the following code to sensors.py:
sensors.py
# sensors.py class Sensor: def __init__(self, type): self.type = type def read_value(self): # Simulate reading a sensor value return 42
Create a main program file and import the package modules:
# main.py from my_robot_package.motors import Motor from my_robot_package.sensors import Sensor motor = Motor(100) motor.move("forward") sensor = Sensor("Ultrasonic") print(sensor.read_value())
In this example, you create a package my_robot_package with two modules: motors.py and sensors.py. The main program imports and uses the classes from these modules.
my_robot_package
Packages in MicroPython are directories containing modules and an __init__.py file. They help organize and reuse code by grouping related modules together. By creating and using packages, you can improve the structure, maintainability, and reusability of your code.
< Previous Next >