Modernize Python typing across the codebase

Automated via ruff UP006, UP007, UP035, UP045 rules (target: py311):

- Replace `typing.List`, `Dict`, `Tuple`, `Set`, `FrozenSet`, `Type`
  with their built-in equivalents (`list`, `dict`, `tuple`, etc.)
- Replace `typing.Optional[X]` with `X | None`
- Replace `typing.Union[X, Y]` with `X | Y`
- Move `Mapping`, `Sequence`, `Callable`, `Awaitable`,
  `MutableMapping`, `MutableSequence`, `Iterator`, `AsyncIterator`,
  `AsyncGenerator` imports from `typing` to `collections.abc`
- Remove now-unused `typing` imports
- Add `from __future__ import annotations` to 5 files that use
  forward-reference strings in `X | "Y"` annotations
This commit is contained in:
Aleix Conchillo Flaqué
2026-04-16 09:16:53 -07:00
parent 12b8af3d89
commit b3bb6fdaa5
283 changed files with 2902 additions and 3020 deletions

View File

@@ -52,7 +52,7 @@ class TestDirectFunction(unittest.TestCase):
self.assertEqual(func.properties, {})
async def my_function_simple_params(
params: FunctionCallParams, name: str, age: int, height: Union[float, None]
params: FunctionCallParams, name: str, age: int, height: float | None
):
return {"status": "success"}, None
@@ -70,7 +70,7 @@ class TestDirectFunction(unittest.TestCase):
params: FunctionCallParams,
address_lines: list[str],
nickname: str | int | float,
extra: Optional[dict[str, str]],
extra: dict[str, str] | None,
):
return {"status": "success"}, None
@@ -134,7 +134,7 @@ class TestDirectFunction(unittest.TestCase):
self.assertEqual(func.required, [])
async def my_function_simple_params(
params: FunctionCallParams, name: str, age: int, height: Union[float, None] = None
params: FunctionCallParams, name: str, age: int, height: float | None = None
):
return {"status": "success"}, None
@@ -143,9 +143,9 @@ class TestDirectFunction(unittest.TestCase):
async def my_function_complex_params(
params: FunctionCallParams,
address_lines: Optional[list[str]],
address_lines: list[str] | None,
nickname: str | int = "Bud",
extra: Optional[dict[str, str]] = None,
extra: dict[str, str] | None = None,
):
return {"status": "success"}, None
@@ -154,7 +154,7 @@ class TestDirectFunction(unittest.TestCase):
def test_property_descriptions_are_set_from_function(self):
async def my_function(
params: FunctionCallParams, name: str, age: int, height: Union[float, None]
params: FunctionCallParams, name: str, age: int, height: float | None
):
"""
This is a test function.

View File

@@ -7,7 +7,6 @@
import asyncio
import unittest
from dataclasses import dataclass, field
from typing import List
from pipecat.frames.frames import (
DataFrame,
@@ -35,7 +34,7 @@ class BroadcastTestFrame(DataFrame):
text: str = ""
value: int = 0
items: List[str] = field(default_factory=list)
items: list[str] = field(default_factory=list)
class TestFrameProcessor(unittest.IsolatedAsyncioTestCase):
@@ -191,8 +190,8 @@ class TestFrameProcessor(unittest.IsolatedAsyncioTestCase):
async def test_broadcast_frame(self):
"""Test that broadcast_frame creates two separate frames with fresh IDs."""
downstream_frames: List[Frame] = []
upstream_frames: List[Frame] = []
downstream_frames: list[Frame] = []
upstream_frames: list[Frame] = []
class BroadcastTestProcessor(FrameProcessor):
async def process_frame(self, frame: Frame, direction: FrameDirection):
@@ -205,7 +204,7 @@ class TestFrameProcessor(unittest.IsolatedAsyncioTestCase):
await self.push_frame(frame, direction)
class CaptureProcessor(FrameProcessor):
def __init__(self, capture_list: List[Frame], direction: FrameDirection):
def __init__(self, capture_list: list[Frame], direction: FrameDirection):
super().__init__()
self._capture_list = capture_list
self._capture_direction = direction
@@ -256,9 +255,9 @@ class TestFrameProcessor(unittest.IsolatedAsyncioTestCase):
async def test_broadcast_frame_instance(self):
"""Test that broadcast_frame_instance shallow-copies all fields except id and name."""
downstream_frames: List[Frame] = []
upstream_frames: List[Frame] = []
original_frame: List[Frame] = []
downstream_frames: list[Frame] = []
upstream_frames: list[Frame] = []
original_frame: list[Frame] = []
class BroadcastInstanceTestProcessor(FrameProcessor):
async def process_frame(self, frame: Frame, direction: FrameDirection):
@@ -273,7 +272,7 @@ class TestFrameProcessor(unittest.IsolatedAsyncioTestCase):
await self.push_frame(frame, direction)
class CaptureProcessor(FrameProcessor):
def __init__(self, capture_list: List[Frame], direction: FrameDirection):
def __init__(self, capture_list: list[Frame], direction: FrameDirection):
super().__init__()
self._capture_list = capture_list
self._capture_direction = direction
@@ -346,7 +345,7 @@ class TestFrameProcessor(unittest.IsolatedAsyncioTestCase):
This test simulates issue #3524 where an InterruptionFrame during slow
processing would cause terminal frames to be lost, freezing the pipeline.
"""
received_frames: List[Frame] = []
received_frames: list[Frame] = []
class DelayAndInterruptProcessor(FrameProcessor):
"""This processor delays processing and then generates an interruption.
@@ -398,7 +397,7 @@ class TestFrameProcessor(unittest.IsolatedAsyncioTestCase):
Similar to test_terminal_frames_survive_interruption but specifically
for StopFrame.
"""
received_frames: List[Frame] = []
received_frames: list[Frame] = []
class DelayAndInterruptProcessor(FrameProcessor):
"""This processor delays processing and then generates an interruption."""

View File

@@ -289,7 +289,7 @@ class TestPipelineTask(unittest.IsolatedAsyncioTestCase):
task.run(PipelineTaskParams(loop=asyncio.get_event_loop())),
timeout=1.0,
)
except asyncio.TimeoutError:
except TimeoutError:
pass
assert upstream_received
@@ -317,7 +317,7 @@ class TestPipelineTask(unittest.IsolatedAsyncioTestCase):
task.run(PipelineTaskParams(loop=asyncio.get_event_loop())),
timeout=1.0,
)
except asyncio.TimeoutError:
except TimeoutError:
pass
assert upstream_received
@@ -346,7 +346,7 @@ class TestPipelineTask(unittest.IsolatedAsyncioTestCase):
task.run(PipelineTaskParams(loop=asyncio.get_event_loop())),
timeout=1.0,
)
except asyncio.TimeoutError:
except TimeoutError:
pass
assert "First" in upstream_texts
@@ -382,7 +382,7 @@ class TestPipelineTask(unittest.IsolatedAsyncioTestCase):
task.run(PipelineTaskParams(loop=asyncio.get_event_loop())),
timeout=1.0,
)
except asyncio.TimeoutError:
except TimeoutError:
pass
assert heartbeats_counter == expected_heartbeats
@@ -417,7 +417,7 @@ class TestPipelineTask(unittest.IsolatedAsyncioTestCase):
task.run(PipelineTaskParams(loop=asyncio.get_event_loop())),
timeout=0.6,
)
except asyncio.TimeoutError:
except TimeoutError:
pass
log_text = log_output.getvalue()
@@ -441,7 +441,7 @@ class TestPipelineTask(unittest.IsolatedAsyncioTestCase):
task.run(PipelineTaskParams(loop=asyncio.get_event_loop())),
timeout=0.3,
)
except asyncio.TimeoutError:
except TimeoutError:
assert True
else:
assert False

View File

@@ -10,7 +10,8 @@ Verifies that Language enums, raw strings (e.g. "de-DE"), and unrecognized
strings are all resolved correctly at both init time and runtime update time.
"""
from typing import AsyncGenerator, Optional
from collections.abc import AsyncGenerator
from typing import Optional
from unittest.mock import patch
import pytest
@@ -45,7 +46,7 @@ class _TestTTSService(TTSService):
async def run_tts(self, text: str, context_id: str) -> AsyncGenerator[Frame, None]:
yield # pragma: no cover
def language_to_service_language(self, language: Language) -> Optional[str]:
def language_to_service_language(self, language: Language) -> str | None:
return resolve_language(language, _LANGUAGE_MAP, use_base_code=True)
@@ -64,7 +65,7 @@ class _TestSTTService(STTService):
async def process_audio_frame(self, frame, direction):
pass # pragma: no cover
def language_to_service_language(self, language: Language) -> Optional[str]:
def language_to_service_language(self, language: Language) -> str | None:
return resolve_language(language, _LANGUAGE_MAP, use_base_code=True)

View File

@@ -24,8 +24,8 @@ verifies TTSTextFrame ordering relative to LLMFullResponseEndFrame.
import asyncio
import unittest
from collections.abc import AsyncGenerator, Sequence
from dataclasses import dataclass
from typing import AsyncGenerator, List, Sequence, Tuple
import pytest
@@ -215,7 +215,7 @@ class MockWebSocketPauseTTSService(TTSService):
def _assert_group_ordering(
down_frames: Sequence[Frame],
expected_groups: List[Tuple[str, str]],
expected_groups: list[tuple[str, str]],
) -> None:
"""Assert two (or more) TTS+FooFrame groups are in strict order.
@@ -240,7 +240,7 @@ def _assert_group_ordering(
)
# Build groups: everything up to and including each FooFrame.
groups: List[List[Frame]] = []
groups: list[list[Frame]] = []
prev = 0
for idx in foo_indices:
groups.append(relevant[prev : idx + 1])
@@ -298,7 +298,7 @@ def _assert_group_ordering(
_GROUPS = [("test 1", "1"), ("test 2", "2")]
def _make_frames_no_sleep() -> List[Frame]:
def _make_frames_no_sleep() -> list[Frame]:
"""Return two TTSSpeakFrame+FooFrame pairs sent back-to-back.
Only correct for services that pause downstream processing until the audio

View File

@@ -6,7 +6,6 @@
import asyncio
import unittest
from typing import List
from pipecat.audio.vad.vad_analyzer import VADAnalyzer, VADParams, VADState
from pipecat.audio.vad.vad_controller import VADController
@@ -125,7 +124,7 @@ class TestVADController(unittest.IsolatedAsyncioTestCase):
analyzer = MockVADAnalyzer()
controller = VADController(analyzer)
pushed_frames: List[tuple] = []
pushed_frames: list[tuple] = []
@controller.event_handler("on_push_frame")
async def on_push_frame(_controller, frame: Frame, direction: FrameDirection):
@@ -143,7 +142,7 @@ class TestVADController(unittest.IsolatedAsyncioTestCase):
analyzer = MockVADAnalyzer()
controller = VADController(analyzer)
broadcast_calls: List[tuple] = []
broadcast_calls: list[tuple] = []
@controller.event_handler("on_broadcast_frame")
async def on_broadcast_frame(_controller, frame_cls, **kwargs):
@@ -192,7 +191,7 @@ class TestVADController(unittest.IsolatedAsyncioTestCase):
analyzer = MockVADAnalyzer()
controller = VADController(analyzer)
broadcast_calls: List[tuple] = []
broadcast_calls: list[tuple] = []
@controller.event_handler("on_broadcast_frame")
async def on_broadcast_frame(_controller, frame_cls, **kwargs):

View File

@@ -5,7 +5,6 @@
#
import unittest
from typing import List
from pipecat.audio.vad.vad_analyzer import VADAnalyzer, VADState
from pipecat.frames.frames import (
@@ -22,7 +21,7 @@ from pipecat.tests.utils import run_test
class MockVADAnalyzer(VADAnalyzer):
"""A mock VAD analyzer that returns states from a predefined sequence."""
def __init__(self, states: List[VADState]):
def __init__(self, states: list[VADState]):
super().__init__(sample_rate=16000)
self._states = list(states)
self._call_index = 0