Skip to content

Readability: Deep nesting in linux.py LinuxBackend.__init__ engine selection #29

@m96-chan

Description

@m96-chan

Summary

The engine selection logic in LinuxBackend.init has deeply nested try/except blocks that are hard to follow.

Location

src/proctap/backends/linux.py:1196-1272

Problem

The code has 3-4 levels of nesting with try/except blocks for fallback logic:

if detected_engine == "pipewire-native":
    try:
        self._strategy = PipeWireNativeStrategy(...)
    except RuntimeError as e:
        try:
            self._strategy = PipeWireStrategy(...)
        except RuntimeError as e2:
            self._strategy = PulseAudioStrategy(...)
elif detected_engine == "pulse":
    self._strategy = PulseAudioStrategy(...)
elif detected_engine == "pipewire":
    try:
        self._strategy = PipeWireStrategy(...)
    except RuntimeError as e:
        self._strategy = PulseAudioStrategy(...)

Impact

  • Hard to follow the fallback chain
  • Duplicated fallback logic
  • Complex error handling

Suggested Fix

Use a strategy chain pattern:

def _create_strategy(self, pid, sample_rate, channels, sample_width, engine):
    strategies = self._get_strategy_chain(engine)
    
    for strategy_class in strategies:
        try:
            return strategy_class(pid=pid, sample_rate=sample_rate, ...)
        except RuntimeError as e:
            logger.warning(f"{strategy_class.__name__} failed: {e}")
            continue
    
    raise RuntimeError("No audio strategy available")

def _get_strategy_chain(self, engine: str) -> list[type]:
    chains = {
        "pipewire-native": [PipeWireNativeStrategy, PipeWireStrategy, PulseAudioStrategy],
        "pipewire": [PipeWireStrategy, PulseAudioStrategy],
        "pulse": [PulseAudioStrategy],
    }
    return chains.get(engine, chains["pulse"])

Labels

readability, refactor

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions