🔍 Code Extractor

class switch

Maturity: 38

A Python implementation of a switch-case statement helper that mimics C-style switch behavior with fall-through support.

File:
/tf/active/vicechatdev/datacapture_integrated.py
Lines:
105 - 124
Complexity:
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

    A metaclass that customizes the isinstance() behavior for type variable-like classes by delegating to a backported type variable implementation.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/typing_extensions.py
  • class MoveOperations 31.5% similar

    An enumeration-style class that defines constants for file move operation behaviors, specifically whether to overwrite existing files or perform no operation.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/sharepoint/files/move_operations.py
  • class _DictSAXHandler 30.8% similar

    A SAX (Simple API for XML) event handler that converts XML documents into Python dictionaries, with extensive configuration options for handling attributes, namespaces, CDATA, and structure.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/xmltodict.py
  • function IntVar 30.0% similar

    A wrapper function that creates a TypeVar using Python's typing module, intended to represent integer type variables.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/typing_extensions.py
  • function is_string_type 29.7% similar

    Checks if a given value is a string type, with compatibility for both Python 2 and Python 3.

    From: /tf/active/vicechatdev/SPFCsync/venv/lib64/python3.11/site-packages/office365/runtime/compat.py
← Back to Browse