pygame-ce icon indicating copy to clipboard operation
pygame-ce copied to clipboard

pygame.event.Event compatability with TypedDict

Open sus-pe opened this issue 3 months ago • 2 comments
trafficstars

Description Hi, I'd like to be able to create my pygame.event.Event objects using TypedDicts that specify the explicit form the event type should contain. For example:

class PygameMouseMotion(TypedDict):
    pos: tuple[WindowX, WindowY]
    rel: tuple[int, int]
    buttons: tuple[LeftMouseBit, MiddleMouseBit, RightMouseBit]

@dataclass(frozen=True)
class MouseMotion:
    x: WindowX
    y: WindowY
    dx: int = 0
    dy: int = 0
    left: Bit = Bit.zero
    middle: Bit = Bit.zero
    right: Bit = Bit.zero

    def as_pygame(self) -> PygameMouseMotion:
        return PygameMouseMotion(
            pos=(self.x, self.y),
            rel=(self.dx, self.dy),
            buttons=(self.left, self.middle, self.right),
        )

async def test_mouse(game: Game) -> None:
    expected_mouse = MouseMotion.from_xy(x=0, y=0)
    pygame.event.post(
        pygame.event.Event(
            pygame.MOUSEMOTION,
            expected_mouse.as_pygame(),
        )
    )

    mouse = await game.wait_for_next_mouse_motion()
    assert mouse == expected_mouse

This snippet won't pass mypy: tests\acceptance\mouse_test.py:12: error: Argument 2 to "Event" has incompatible type "PygameMouseMotion"; expected "dict[str, Any]" [arg-type]

If event.dict field had been type annotated with Mapping it would have worked fin.

Any thoughts? Would this break anythong?

sus-pe avatar Aug 16 '25 06:08 sus-pe