class switch
A Python implementation of a switch-case statement helper that mimics C-style switch behavior with fall-through support.
/tf/active/vicechatdev/datacapture_integrated.py
105 - 124
simple
Purpose
This class provides a Pythonic way to implement switch-case logic, particularly useful for menu selection systems. It allows matching a value against multiple cases and supports fall-through behavior (continuing to execute subsequent cases after a match). The class is designed to be used with Python's for-in loop syntax to create readable switch-case structures.
Source Code
class switch(object):
# Helper function to build long "case" choice functions - used in menu selection
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
bases |
object | - |
Parameter Details
value: The value to be matched against in case statements. This is the expression being switched on, similar to the value in a C switch statement. Can be any comparable Python object (string, integer, etc.).
Return Value
Instantiation returns a switch object that can be iterated over. The match() method returns a boolean: True if the case should be entered (either due to matching, fall-through, or default case), False otherwise.
Class Interface
Methods
__init__(self, value) -> None
Purpose: Initialize the switch object with a value to match against and set initial state
Parameters:
value: The value that will be compared against case arguments
Returns: None (constructor)
__iter__(self) -> Iterator
Purpose: Make the switch object iterable, yielding the match method once then stopping
Returns: Generator that yields the match method once, then raises StopIteration
match(self, *args) -> bool
Purpose: Determine whether to enter a case suite by checking if the switch value matches any of the provided arguments
Parameters:
args: Variable number of values to match against. If empty, acts as a default case. If self.value is in args, the case matches.
Returns: True if the case should be entered (match found, fall-through active, or default case), False otherwise
Attributes
| Name | Type | Description | Scope |
|---|---|---|---|
value |
Any | The value being switched on, set during initialization and compared against case arguments | instance |
fall |
bool | Fall-through flag. Initially False. Set to True when a case matches, causing all subsequent cases to match (mimicking C switch fall-through behavior) | instance |
Usage Example
# Basic usage for menu selection
for case in switch(user_choice):
if case('option1'):
print('Handling option 1')
break
if case('option2', 'option3'):
print('Handling option 2 or 3')
break
if case():
print('Default case')
break
# Example with fall-through (no break)
choice = 2
for case in switch(choice):
if case(1):
print('Case 1')
# No break - will fall through
if case(2):
print('Case 2')
# No break - will fall through
if case(3):
print('Case 3')
break
Best Practices
- Always use the class within a for-in loop: 'for case in switch(value):'
- Call the match() method using 'if case(...)' syntax within the loop
- Use 'break' after each case block to prevent fall-through unless fall-through is desired
- Call case() with no arguments to create a default case that always matches
- Multiple values can be passed to a single case() call to match any of them
- The iterator yields the match method only once, so the loop body executes exactly once
- Once a case matches, self.fall is set to True, causing all subsequent cases to match (fall-through behavior)
- This class is stateful - each instantiation maintains its own match state
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function python2sort 39.7% similar
-
class QueryIteration 34.1% similar
-
class FlaskUser 33.1% similar
-
class Generator 32.7% similar
-
class Application 31.1% similar