### Python Switch Example vs. Raw Dictionary Source: https://github.com/mikeckennedy/python-switch/blob/master/README.md Compares the implementation of a command-handling loop using switchlang against a traditional Python dictionary lookup. It highlights how switchlang can offer more explicit intent and potentially better readability for complex conditional logic. ```python # with python-switch: while True: action = get_action(action) with switch(action) as s: s.case(['c', 'a'], create_account) s.case('l', log_into_account) s.case('r', register_cage) s.case('u', update_availability) s.case(['v', 'b'], view_bookings) s.case('x', exit_app) s.case('', lambda: None) s.case(range(1,6), lambda: set_level(action)) s.default(unknown_command) print('Result is {}'.format(s.result)) ``` ```python # with raw dicts while True: action = get_action(action) switch = { 'c': create_account, 'a': create_account, 'l': log_into_account, 'r': register_cage, 'u': update_availability, 'v': view_bookings, 'b': view_bookings, 'x': exit_app, 1: lambda: set_level(action), 2: lambda: set_level(action), 3: lambda: set_level(action), 4: lambda: set_level(action), 5: lambda: set_level(action), '': lambda: None, } result = switch.get(action, unknown_command)() print('Result is {}'.format(result)) ``` -------------------------------- ### Python Switch Example with Cases and Default Source: https://github.com/mikeckennedy/python-switch/blob/master/README.md Demonstrates the basic usage of the switchlang library, showing how to define cases with specific values and actions, including a default action for unmatched inputs. It utilizes the 'with' statement to manage the switch block and lambda functions for inline actions. ```python from switchlang import switch def main(): num = 7 val = input("Enter a character, a, b, c or any other: ") with switch(val) as s: s.case('a', process_a) s.case('b', lambda: process_with_data(val, num, 'other values still')) s.default(process_any) def process_a(): print("Found A!") def process_any(): print("Found Default!") def process_with_data(*value): print("Found with data: {}".format(value)) main() ``` -------------------------------- ### Install switchlang via pip Source: https://github.com/mikeckennedy/python-switch/blob/master/README.md Provides the command-line instruction to install the switchlang library using pip, the standard package installer for Python. This is a prerequisite for using the library in any Python project. ```bash pip install switchlang ``` -------------------------------- ### Use closed_range for Inclusive Ranges in Switch Source: https://context7.com/mikeckennedy/python-switch/llms.txt Illustrates the use of `closed_range` to create inclusive ranges for matching values in switch cases, contrasting it with Python's default half-open `range`. This is useful for scenarios where both start and end values should be considered part of the match. ```python from switchlang import switch, closed_range def get_rating_label(stars): """Convert star rating to label using closed ranges.""" with switch(stars) as s: s.case(closed_range(1, 2), lambda: "Poor") s.case(closed_range(3, 3), lambda: "Average") s.case(closed_range(4, 5), lambda: "Excellent") s.default(lambda: "Invalid rating") return s.result for stars in [1, 2, 3, 4, 5, 6]: print(f"{stars} stars: {get_rating_label(stars)}") # Comparison: range vs closed_range def compare_ranges(value): print(f"\nValue: {value}") # Using range (half-open: excludes 5) with switch(value) as s: s.case(range(1, 5), lambda: "matched range(1,5)") s.default(lambda: "no match for range") print(f" range(1, 5): {s.result}") # Using closed_range (inclusive: includes 5) with switch(value) as s: s.case(closed_range(1, 5), lambda: "matched closed_range(1,5)") s.default(lambda: "no match for closed_range") print(f" closed_range(1, 5): {s.result}") compare_ranges(5) ``` -------------------------------- ### Implement Switch Statement with Basic Cases in Python Source: https://context7.com/mikeckennedy/python-switch/llms.txt Demonstrates the core functionality of the `switchlang` library, using the `switch` context manager with `case()` and `default()` methods to handle different actions based on an input value. It shows how to process commands and map integer values to specific outputs, including error handling for duplicate cases and missing defaults. ```python from switchlang import switch def process_command(action): """Handle user commands with switch statement.""" with switch(action) as s: s.case('c', lambda: "Creating new account...") s.case('l', lambda: "Logging in...") s.case('q', lambda: "Quitting application") s.default(lambda: f"Unknown command: {action}") return s.result # Usage examples print(process_command('c')) print(process_command('l')) print(process_command('x')) # Switch with integer values def get_day_name(day_num): with switch(day_num) as s: s.case(1, lambda: "Monday") s.case(2, lambda: "Tuesday") s.case(3, lambda: "Wednesday") s.case(4, lambda: "Thursday") s.case(5, lambda: "Friday") s.case(6, lambda: "Saturday") s.case(7, lambda: "Sunday") s.default(lambda: "Invalid day") return s.result print(get_day_name(3)) # Error handling - duplicate cases raise ValueError try: with switch('test') as s: s.case(1, lambda: 'first') s.case(1, lambda: 'duplicate') # Raises ValueError except ValueError as e: print(f"Error: {e}") # Error handling - missing default with no match raises Exception try: with switch('unknown') as s: s.case('a', lambda: 'A') s.case('b', lambda: 'B') # No default and 'unknown' doesn't match any case except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Python If/Elif/Else for Action Handling Source: https://github.com/mikeckennedy/python-switch/blob/master/README.md Demonstrates a common pattern using if, elif, and else statements to handle various user actions. This approach can become verbose and is prone to errors such as uninitialized variables or duplicate case definitions. ```python while True: action = get_action(action) if action == 'c' or action == 'a': result = create_account() elif action == 'l': result = log_into_account() elif action == 'r': result = register_cage() elif action == 'a': result = update_availability() elif action == 'v' or action == 'b': result = view_bookings() elif action == 'x': result = exit_app() elif action in {1, 2, 3, 4, 5}: result = set_level(action) else: unknown_command() print('Result is {}'.format(result)) ``` -------------------------------- ### Python Switch with Complex Return Values Source: https://context7.com/mikeckennedy/python-switch/llms.txt Demonstrates using the switchlang library to handle different user types and return complex dictionary values based on the user's role. It shows how to define cases with lambda functions for dynamic return values and a default case for unhandled types. The result is accessed after the 'with' block. ```python from switchlang import switch def get_user_info(user_type): with switch(user_type) as s: s.case('admin', lambda: {'role': 'admin', 'permissions': ['read', 'write', 'delete']}) s.case('editor', lambda: {'role': 'editor', 'permissions': ['read', 'write']}) s.case('viewer', lambda: {'role': 'viewer', 'permissions': ['read']}) s.default(lambda: {'role': 'guest', 'permissions': []}) return s.result info = get_user_info('editor') print(f"Role: {info['role']}, Permissions: {info['permissions']}") ``` -------------------------------- ### Match Numeric Sequences with Ranges in Python Source: https://context7.com/mikeckennedy/python-switch/llms.txt Demonstrates the use of Python's built-in `range()` object with the `case()` method in `switchlang` for matching numeric sequences. This is particularly useful for defining score ranges for grading or other continuous numeric conditions. ```python from switchlang import switch def grade_score(score): """Convert numeric score to letter grade.""" with switch(score) as s: s.case(range(90, 101), lambda: "A") s.case(range(80, 90), lambda: "B") s.case(range(70, 80), lambda: "C") s.case(range(60, 70), lambda: "D") s.case(range(0, 60), lambda: "F") s.default(lambda: "Invalid score") return s.result scores = [95, 82, 75, 61, 45, 105] for score in scores: print(f"Score {score}: Grade {grade_score(score)}") ``` -------------------------------- ### Group Multiple Values to Single Actions with Lists in Python Source: https://context7.com/mikeckennedy/python-switch/llms.txt Illustrates how to use lists with the `case()` method in `switchlang` to map multiple values to a single action. This is useful for grouping related inputs, such as vowels, digits, or months within a fiscal quarter, improving code conciseness. ```python from switchlang import switch def classify_char(char): """Classify a character as vowel, consonant, or digit.""" with switch(char.lower()) as s: s.case(['a', 'e', 'i', 'o', 'u'], lambda: "vowel") s.case(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], lambda: "digit") s.default(lambda: "consonant") return s.result print(classify_char('A')) print(classify_char('b')) print(classify_char('5')) # Multiple actions with grouped cases def get_quarter(month): """Get fiscal quarter from month number.""" with switch(month) as s: s.case([1, 2, 3], lambda: "Q1") s.case([4, 5, 6], lambda: "Q2") s.case([7, 8, 9], lambda: "Q3") s.case([10, 11, 12], lambda: "Q4") s.default(lambda: "Invalid month") return s.result for month in [1, 6, 12, 13]: print(f"Month {month}: {get_quarter(month)}") ``` -------------------------------- ### Enable Fallthrough Behavior in Switch Cases Source: https://context7.com/mikeckennedy/python-switch/llms.txt Demonstrates how to enable C-style fallthrough behavior in switch cases using the `fallthrough=True` parameter. When enabled, execution continues to the next case after a match, allowing multiple actions or conditions to be processed sequentially. ```python from switchlang import switch def process_with_fallthrough(level): """Demonstrate fallthrough behavior - executes multiple cases.""" actions = [] with switch(level) as s: s.case(1, lambda: actions.append("Basic access") or "basic") s.case(2, lambda: actions.append("Standard features") or "standard", fallthrough=True) s.case(3, lambda: actions.append("Premium features") or "premium", fallthrough=True) s.case(4, lambda: actions.append("Admin access") or "admin") s.default(lambda: actions.append("Guest only") or "guest") return actions, s.result # Level 2 falls through to 3, then 4 (stops because no fallthrough) actions, result = process_with_fallthrough(2) print(f"Level 2 actions: {actions}") print(f"Final result: {result}") # Level 4 doesn't fall through actions, result = process_with_fallthrough(4) print(f"Level 4 actions: {actions}") # Fallthrough to default def cascade_example(value): visited = [] with switch(value) as s: s.case('start', lambda: visited.append('started'), fallthrough=True) s.default(lambda: visited.append('finished')) return visited print(cascade_example('start')) print(cascade_example('other')) ``` -------------------------------- ### Python Switch Statement for Action Handling Source: https://github.com/mikeckennedy/python-switch/blob/master/README.md Presents an alternative using a custom 'switch' statement for handling actions, offering a more declarative and potentially safer approach. This method guards against duplicate cases and provides a structured way to manage default actions and results. ```python while True: action = get_action(action) with switch(action) as s: s.case(['c', 'a'], create_account) s.case('l', log_into_account) s.case('r', register_cage) s.case('u', update_availability) s.case(['v', 'b'], view_bookings) s.case('x', exit_app) s.case('', lambda: None) s.case(range(1,6), lambda: set_level(action)) s.default(unknown_command) print('Result is {}'.format(s.result)) ``` -------------------------------- ### Python Switch with List of Cases Source: https://github.com/mikeckennedy/python-switch/blob/master/README.md Illustrates how to map multiple discrete values (provided as a list) to a single action within a switch statement. This feature enhances code readability by grouping related cases that should trigger the same logic. ```python # with lists: value = 4 # matches even number case with switch(value) as s: s.case([1, 3, 5, 7], lambda: ...) s.case([0, 2, 4, 6, 8], lambda: ...) s.default(lambda: ...) ``` -------------------------------- ### Categorize Age using Switch Source: https://context7.com/mikeckennedy/python-switch/llms.txt Demonstrates how to categorize a person's age into different groups (Child, Teenager, Adult, Senior) using the switchlang library. It utilizes Python's range function within the switch cases. ```python from switchlang import switch def categorize_age(age): """Categorize person by age group.""" with switch(age) as s: s.case(range(0, 13), lambda: "Child") s.case(range(13, 20), lambda: "Teenager") s.case(range(20, 65), lambda: "Adult") s.case(range(65, 150), lambda: "Senior") s.default(lambda: "Invalid age") return s.result print(categorize_age(8)) # Output: Child print(categorize_age(16)) # Output: Teenager print(categorize_age(35)) # Output: Adult print(categorize_age(70)) # Output: Senior ``` -------------------------------- ### Python Switch with Range of Cases Source: https://github.com/mikeckennedy/python-switch/blob/master/README.md Demonstrates mapping a continuous sequence of values (defined by a range object) to a single action. This is useful for handling conditions where a value falls within a specific numerical interval. ```python # with ranges: value = 4 # matches first case with switch(value) as s: s.case(range(1, 6), lambda: ...) s.case(range(6, 10), lambda: ...) s.default(lambda: ...) ``` -------------------------------- ### Access Switch Case Result using .result Property Source: https://context7.com/mikeckennedy/python-switch/llms.txt Explains how to retrieve the return value of the executed switch case using the `.result` property. This property must be accessed after the `with` block has concluded, as accessing it within the block will raise an exception. ```python from switchlang import switch def calculate(operation, a, b): """Perform calculation and return result.""" with switch(operation) as s: s.case('+', lambda: a + b) s.case('-', lambda: a - b) s.case('*', lambda: a * b) s.case('/', lambda: a / b if b != 0 else "Division by zero") s.default(lambda: "Unknown operation") return s.result print(calculate('+', 10, 5)) print(calculate('-', 10, 5)) print(calculate('*', 10, 5)) print(calculate('/', 10, 5)) print(calculate('%', 10, 5)) ``` -------------------------------- ### Python Switch Error Handling: Accessing Result Before Execution Source: https://context7.com/mikeckennedy/python-switch/llms.txt Illustrates an error scenario in switchlang where accessing 's.result' before the switch block has completed execution raises an exception. This highlights the importance of accessing the result only after the 'with' block has finished. ```python from switchlang import switch try: s = switch('test') print(s.result) # Raises exception except Exception as e: print(f"Error: {e}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.