partial is a callable factory from Python’s functools module. It accepts an existing function plus positional or keyword arguments, then returns a new function that calls the original with those values pre-bound. This replaces repetitive wrapper definitions while preserving a simple function interface. section 3.11
A robot motor library can define one movement function and derive named controls from it. Each derived function changes only the values needed for a direction or maneuver, while duration and speed remain available as arguments. section 3.11 section 3.12
Common motor controls bind movement parameters as follows:
- forward = partial(movement) uses movement’s defaults. section 3.11
- backward = partial(movement, factor_r=-1, factor_l=-1) reverses both motors. section 3.11
- right and left reduce one motor’s factor to create a turn. section 3.11
- spin_right and spin_left bind opposite motor directions. section 3.11
Reusable motor controls
from functools import partial forward = partial(movement) backward = partial(movement, factor_r=-1, factor_l=-1) right = partial(movement, factor_r=0.5) left = partial(movement, factor_l=0.5) spin_right = partial(movement, factor_r=-1, factor_l=1) spin_left = partial(movement, factor_r=1, factor_l=-1) After importing the motor module, calls such as motor.forward(), motor.right(0.5), and motor.spin_left(2) operate the robot through the shared movement function. section 3.11
Listing 3.8 motor.py: Simplifying the way functions are defined
#!/usr/bin/env python3
from adafruit_crickit import crickit
import time
import os
from functools import partial
DC_ADJUST_R = float(os.environ.get('ROBO_DC_ADJUST_R', '1'))
DC_ADJUST_L = float(os.environ.get('ROBO_DC_ADJUST_L', '1'))
ADJUST = dict(R=DC_ADJUST_R, L=DC_ADJUST_L)
MOTOR = dict(R=crickit.dc_motor_1, L=crickit.dc_motor_2)
THROTTLE_SPEED = {0: 0, 1: 0.5, 2: 0.7, 3: 0.9}
def set_throttle(name, speed, factor=1):
MOTOR[name].throttle = THROTTLE_SPEED[speed] * ADJUST[name] * factor
def movement(duration=0.2, speed=3, factor_r=1, factor_l=1):
set_throttle('R', speed, factor_r)
set_throttle('L', speed, factor_l)
time.sleep(duration)
set_throttle('R', 0)
set_throttle('L', 0)
forward = partial(movement)
backward = partial(movement, factor_r=-1, factor_l=-1)
right = partial(movement, factor_r=0.5)
left = partial(movement, factor_l=0.5)
spin_right = partial(movement, factor_r=-1, factor_l=1)
spin_left = partial(movement, factor_r=1, factor_l=-1)
noop = lambda: None
Inspect the complete motor.py implementation, including the shared movement function, throttle configuration, partial-based controls, and hardware imports. section 3.11

