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, commonly used for menu selection and multi-branch conditionals. It supports fall-through behavior (like C's switch statement) where once a case matches, all subsequent cases execute until explicitly stopped. 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 'switch(value)' in C-style languages. Can be any comparable Python object (string, int, etc.).
Return Value
Instantiation returns a switch object that can be iterated over. The match() method returns a boolean: True if the case should execute (either because it matches, fall-through is active, or no arguments provided for 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 to be compared against in case statements; can be any comparable type
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 comparing arguments against the stored value
Parameters:
*args: Variable number of values to match against; if empty, acts as default case; if value matches any arg, returns True and enables fall-through
Returns: Boolean: True if case should execute (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 in match() calls | instance |
fall |
bool | Fall-through flag; initially False, set to True when a case matches, causing all subsequent cases to execute | instance |
Usage Example
# Basic switch-case usage
value = 2
for case in switch(value):
if case(1):
print('Case 1')
break
if case(2, 3):
print('Case 2 or 3')
break
if case(4):
print('Case 4')
break
if case():
print('Default case')
break
# Menu selection example
user_choice = 'save'
for case in switch(user_choice):
if case('save', 's'):
print('Saving file...')
break
if case('load', 'l'):
print('Loading file...')
break
if case('quit', 'q'):
print('Quitting...')
break
if case():
print('Invalid option')
# Fall-through example (without break)
value = 2
for case in switch(value):
if case(1):
print('One')
if case(2):
print('Two')
if case(3):
print('Three')
if case():
print('Done')
Best Practices
- Always use the switch class within a for-in loop: 'for case in switch(value):'
- Use break statements after each case to prevent fall-through behavior (unless fall-through is desired)
- Call case() with no arguments to create a default case that always matches
- The match() method can accept multiple values: case(1, 2, 3) matches if value is 1, 2, or 3
- Once a case matches, self.fall is set to True, causing all subsequent cases to execute until the loop breaks
- The iterator yields the match method only once, so the for loop body executes exactly once
- This pattern is most useful for menu systems and multi-way branching where readability is important
- Not thread-safe due to mutable state (self.fall); create separate instances for concurrent use
Similar Components
AI-powered semantic similarity - components with related functionality:
-
class _TypeVarLikeMeta 33.3% similar
-
class MoveOperations 31.5% similar
-
class _DictSAXHandler 30.8% similar
-
function IntVar 30.0% similar
-
function is_string_type 29.7% similar