6. RobotPy Patterns
Three parts of Python that normal tutorials skip, but our code uses everywhere: lambdas, button decorators, and yield.
Summary
Lambdas: read the value again later
Button(lambda: self.robot.rumble_d1)
lambda: expr is a small function without a name. It is the same as:
def nameless():
return self.robot.rumble_d1
Why the lambda? Button(self.robot.rumble_d1) would freeze the startup value forever. Button(lambda: self.robot.rumble_d1) hands over a function, and the button calls it every frame. It always reads the current value.
Decorators: register a function
@self.driver1.POV.DOWN.whenPressed
def _():
self.robot.poseEstimator.set_yaw(0.0)
When Python executes the function definition, @x calls x(your_function). The team button decorator creates and binds a command. The scheduler runs the command when the driver presses the button. In this example, driver 1 POV DOWN resets yaw. The A button has a different heading binding.
Two details you will see in oi.py:
- The function is named
_on purpose. It means: only the decorator uses this name. - The team
whenHeldwrapper useswhileTrue: a press schedules the command, and a release cancels it if it is active. A completed command does not restart while the button remains held. - A normal function bound with
whenHeldruns once. Repeated work needs a generator that continues to yield. whenReleasedschedules its command when the button changes from pressed to released.
Coroutines: a command as a timeline
A function with yield inside is a generator. Its lifecycle:
- You call it. Nothing runs yet. You get a generator object.
- Each time the scheduler steps it, the function runs up to the next
yield, then pauses there. - When the function returns, the scheduler removes the command.
@self.rumble_button_d1.whenPressed
def _():
timer = Timer()
timer.start()
self.driver1.setRumble(1)
while not timer.hasElapsed(0.5):
yield # stop here, continue next frame
self.driver1.setRumble(0)
“Rumble for half a second” reads top to bottom, and the robot keeps driving during the wait. Many of our command bodies are while True: ... yield: do some work, wait a frame, repeat forever (the drivetrain default command is built this way).
Do not use time.sleep() in a command callback or generator on the robot main loop. It blocks other work. Use yield to return control to the scheduler. Use a timer to measure elapsed time.
Try it
Run the code. Then add a second decorated function that prints a different message. Call a_button.press() again.
TinyButton stores only one handler. The second decoration replaces the first handler. Predict which message the next press prints. This is a teaching model, not the team command scheduler.
The code operates in your browser. The page sends nothing to a server and saves your work on this computer. Press Ctrl+Enter to run it.
Tools for these exercises
For exercise 6.1, a conditional expression selects one result:
status = lambda: 'spinning' if motor_speed > 0.1 else 'stopped'
The lambda reads motor_speed when called. The expression returns one of the two strings.
For exercise 6.2, next(gen) advances a generator. Use try and except to handle completion:
try:
next(gen)
except StopIteration:
print('The generator ended.')
while True repeats until the function returns or the loop exits. Count only successful next() calls. Code after the final yield runs on a later call that reaches completion. That call raises StopIteration.
Exercises
6.1 Lambdas read the live value
A lambda re-reads its variables every time it is called. That is why Button(lambda: ...) works: the button asks a fresh question every frame.
PART A: make a lambda status. It returns 'spinning' when motor_speed > 0.1, else 'stopped'.
PART B: make a lambda healthy. It returns True when -60 < motor_speed < 60, else False.
The code operates in your browser. The page sends nothing to a server and saves your work on this computer. Press Ctrl+Enter to run it.
6.2 Step a generator until it ends
Calling a generator function creates a generator object. next(gen) runs its code until the next yield. If the generator ends, next(gen) raises StopIteration.
Write count_frames(gen). Use while True to keep stepping. In a try block, call next(gen), then add 1 to the count. In except StopIteration, return the count. The failed completion attempt must not increase the count.
Three yields require three successful next() calls. A fourth attempt reaches the code after the last yield and reports completion. The checks also verify that this final code runs.
This browser exercise counts yields, not elapsed time. The robot scheduler advances a command generator during its cycles.
The code operates in your browser. The page sends nothing to a server and saves your work on this computer. Press Ctrl+Enter to run it.
6.3 Predict, then measure
This is the while ... yield pattern from the command bodies in oi.py.
PART A: change intake_until_full so the hopper fills in 100 frames instead of 5.
PART B: set prediction to the number of frames a frame counter will report. Make the prediction before you run the checks.
The code operates in your browser. The page sends nothing to a server and saves your work on this computer. Press Ctrl+Enter to run it.
6.4 Extension: start and stop an intake
The fake intake and fake button are supplied. Complete only the two callback bodies.
- In
start_intake(), callintake.set_speed(0.85). - In
stop_intake(), callintake.stop(). - Predict the motor values after press, release, and a second press.
- Select Run checks.
This model calls callbacks directly. It has no scheduler or whenHeld behavior. The real robot uses button bindings, robot flags, and periodic() to select motor commands.
The code operates in your browser. The page sends nothing to a server and saves your work on this computer. Press Ctrl+Enter to run it.
After the lessons
Open robot/oi.py with a mentor. Trace one button binding from the press to the motor command. You now know every Python tool it uses.
Next lesson: 7. RobotPy in Our Robot Code. It uses the real robot libraries on your own computer.