Skip to content

Commit 2ba6cef

Browse files
committed
Bugfix.
1 parent 8a990c2 commit 2ba6cef

File tree

5 files changed

+112
-91
lines changed

5 files changed

+112
-91
lines changed

docs/reST/ref/event.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,7 @@ On Android, the following events can be generated
473473

474474
| :sl:`returns related event class to event type`
475475
| :sg:`event_class(type: int, /) -> type[Event]`
476+
476477
Returns an event class that is correlated with the given event type. If the class to a given event type is not found,
477478
but the type is within the range of valid values for the event type, instead of a ``pygame.event.Event`` subclass,
478479
``pygame.event.Event`` itself will be returned, so don't rely on the retuned class having ``type`` attribute equal to a number.
@@ -615,4 +616,8 @@ On Android, the following events can be generated
615616
``WindowDisplayChanged`` ``WINDOWDISPLAYCHANGED``
616617
============================= ============================= ==========================
617618

619+
.. note::
620+
621+
While instantiating these subclasses, don't pass the ``type`` argument to ``{Class name}.__init__()``
622+
618623
.. ## pygame.event ##

src_c/doc/event_doc.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#define DOC_EVENT_GETGRAB "get_grab() -> bool\ntest if the program is sharing input devices"
1515
#define DOC_EVENT_POST "post(event, /) -> bool\nplace a new event on the queue"
1616
#define DOC_EVENT_CUSTOMTYPE "custom_type() -> int\nmake custom user event type"
17+
#define DOC_EVENT_EVENTCLASS "event_class(type: int, /) -> type[Event]\nreturns related event class to event type"
1718
#define DOC_EVENT_EVENT "Event(type, dict) -> Event\nEvent(type, **attributes) -> Event\npygame object for representing events"
1819
#define DOC_EVENT_EVENT_TYPE "type -> int\nevent type identifier."
1920
#define DOC_EVENT_EVENT_DICT "__dict__ -> dict\nevent attribute dictionary"

src_py/event.py

Lines changed: 101 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
_proxify_event_type,
2626
)
2727

28-
from pygame.base import error
2928
import pygame as pg
3029

3130

@@ -74,22 +73,22 @@ class UnknownEvent(Event):
7473
return UnknownEvent
7574

7675

77-
def event_class(ev_type: int) -> type[EventLike]:
78-
_check_ev_type(ev_type)
76+
def event_class(type: int) -> type[EventLike]:
77+
_check_ev_type(type)
7978

80-
if ev_type not in _events_map:
81-
_events_map[ev_type] = _unknown_event_factory(ev_type)
82-
return _events_map[ev_type]
79+
if type not in _events_map:
80+
_events_map[type] = _unknown_event_factory(type)
81+
return _events_map[type]
8382

8483

8584
class _EventMeta(type):
86-
def _create_of_type(self, type: int, *args, **kwds):
85+
def _create_of_type(cls, type: int, *args, **kwds):
8786
return event_class(type)(*args, **kwds)
8887

89-
def __call__(self, *args: Any, **kwds: Any) -> Any:
90-
if self is Event:
91-
return self._create_of_type(*args, **kwds)
92-
return super(_EventMeta, self).__call__(*args, **kwds)
88+
def __call__(cls, *args: Any, **kwds: Any) -> Any:
89+
if cls is Event:
90+
return cls._create_of_type(*args, **kwds)
91+
return super(_EventMeta, cls).__call__(*args, **kwds)
9392

9493

9594
class Event(metaclass=_EventMeta):
@@ -141,7 +140,11 @@ def __eq__(self, other: Any):
141140

142141
def __repr__(self):
143142
if getattr(self, "_unknown", False):
144-
return f"<{type(self).__module__}.<dynamic>.{type(self).__name__}({self.type} {self.dict})>"
143+
return (
144+
f"<{type(self).__module__}.<dynamic>."
145+
f"{type(self).__name__}({self.type} {self.dict})>"
146+
)
147+
145148
return f"<{type(self).__module__}.{type(self).__qualname__}({self.dict})>"
146149

147150
@property
@@ -163,9 +166,10 @@ def __getattribute__(self, name: str):
163166
def __setattr__(self, name: str, value: Any):
164167
if name == "type":
165168
raise AttributeError(
166-
f"attribute 'type' of 'Event' or its subclass object is protected"
169+
"attribute 'type' of 'Event' or its subclass object is protected"
167170
)
168-
elif name in ("_dict", "dict"):
171+
172+
if name in ("_dict", "dict"):
169173
super().__setattr__(name, value)
170174
else:
171175
self._dict[name] = value
@@ -214,7 +218,7 @@ def custom_type():
214218
global _custom_event
215219

216220
if _custom_event >= pg.NUMEVENTS:
217-
raise error("pygame.event.custom_type made too many event types.")
221+
raise pg.error("pygame.event.custom_type made too many event types.")
218222

219223
_custom_event += 1
220224
return _custom_event - 1
@@ -446,136 +450,141 @@ def _create_class(type: int, name: str, note: str | None):
446450

447451
# for cls in _events_map.values():
448452
# if cls.__name__ == "UserEvent": continue
449-
# print(f"{cls.__name__} = _create_class(pg.{const_find(cls.type, cls.__name__)}, {cls.__qualname__!r}, {cls.__doc__!r})")
453+
# print(
454+
# f"{cls.__name__} = _create_class(pg.{const_find(cls.type, cls.__name__)}, " \
455+
# f"{cls.__qualname__!r}, {cls.__doc__!r})"
456+
# )
450457

451458

452-
ActiveEvent = _create_class(pg.ACTIVEEVENT, 'ActiveEvent', None)
453-
AppTerminating = _create_class(pg.APP_TERMINATING, 'AppTerminating', None)
454-
AppLowMemory = _create_class(pg.APP_LOWMEMORY, 'AppLowMemory', None)
459+
ActiveEvent = _create_class(pg.ACTIVEEVENT, "ActiveEvent", None)
460+
AppTerminating = _create_class(pg.APP_TERMINATING, "AppTerminating", None)
461+
AppLowMemory = _create_class(pg.APP_LOWMEMORY, "AppLowMemory", None)
455462
AppWillEnterBackground = _create_class(
456-
pg.APP_WILLENTERBACKGROUND, 'AppWillEnterBackground', None
463+
pg.APP_WILLENTERBACKGROUND, "AppWillEnterBackground", None
457464
)
458465
AppDidEnterBackground = _create_class(
459-
pg.APP_DIDENTERBACKGROUND, 'AppDidEnterBackground', None
466+
pg.APP_DIDENTERBACKGROUND, "AppDidEnterBackground", None
460467
)
461468
AppWillEnterForeground = _create_class(
462-
pg.APP_WILLENTERFOREGROUND, 'AppWillEnterForeground', None
469+
pg.APP_WILLENTERFOREGROUND, "AppWillEnterForeground", None
463470
)
464471
AppDidEnterForeground = _create_class(
465-
pg.APP_DIDENTERFOREGROUND, 'AppDidEnterForeground', None
472+
pg.APP_DIDENTERFOREGROUND, "AppDidEnterForeground", None
466473
)
467-
ClipboardUpdate = _create_class(pg.CLIPBOARDUPDATE, 'ClipboardUpdate', None)
468-
KeyDown = _create_class(pg.KEYDOWN, 'KeyDown', None)
469-
KeyUp = _create_class(pg.KEYUP, 'KeyUp', None)
470-
KeyMapChanged = _create_class(pg.KEYMAPCHANGED, 'KeyMapChanged', None)
471-
LocaleChanged = _create_class(pg.LOCALECHANGED, 'LocaleChanged', 'Only for SDL 2.0.14+')
472-
MouseMotion = _create_class(pg.MOUSEMOTION, 'MouseMotion', None)
473-
MouseButtonDown = _create_class(pg.MOUSEBUTTONDOWN, 'MouseButtonDown', None)
474-
MouseButtonUp = _create_class(pg.MOUSEBUTTONUP, 'MouseButtonUp', None)
474+
ClipboardUpdate = _create_class(pg.CLIPBOARDUPDATE, "ClipboardUpdate", None)
475+
KeyDown = _create_class(pg.KEYDOWN, "KeyDown", None)
476+
KeyUp = _create_class(pg.KEYUP, "KeyUp", None)
477+
KeyMapChanged = _create_class(pg.KEYMAPCHANGED, "KeyMapChanged", None)
478+
LocaleChanged = _create_class(pg.LOCALECHANGED, "LocaleChanged", "Only for SDL 2.0.14+")
479+
MouseMotion = _create_class(pg.MOUSEMOTION, "MouseMotion", None)
480+
MouseButtonDown = _create_class(pg.MOUSEBUTTONDOWN, "MouseButtonDown", None)
481+
MouseButtonUp = _create_class(pg.MOUSEBUTTONUP, "MouseButtonUp", None)
475482
JoyAxisMotion = _create_class(
476483
pg.JOYAXISMOTION,
477-
'JoyAxisMotion',
484+
"JoyAxisMotion",
478485
'Attribute "joy" is depracated, use "instance_id".',
479486
)
480487
JoyBallMotion = _create_class(
481488
pg.JOYBALLMOTION,
482-
'JoyBallMotion',
489+
"JoyBallMotion",
483490
'Attribute "joy" is depracated, use "instance_id".',
484491
)
485492
JoyHatMotion = _create_class(
486-
pg.JOYHATMOTION, 'JoyHatMotion', 'Attribute "joy" is depracated, use "instance_id".'
493+
pg.JOYHATMOTION, "JoyHatMotion", 'Attribute "joy" is depracated, use "instance_id".'
487494
)
488495
JoyButtonUp = _create_class(
489-
pg.JOYBUTTONUP, 'JoyButtonUp', 'Attribute "joy" is depracated, use "instance_id".'
496+
pg.JOYBUTTONUP, "JoyButtonUp", 'Attribute "joy" is depracated, use "instance_id".'
490497
)
491498
JoyButtonDown = _create_class(
492499
pg.JOYBUTTONDOWN,
493-
'JoyButtonDown',
500+
"JoyButtonDown",
494501
'Attribute "joy" is depracated, use "instance_id".',
495502
)
496-
Quit = _create_class(pg.QUIT, 'Quit', None)
503+
Quit = _create_class(pg.QUIT, "Quit", None)
497504
SysWMEvent = _create_class(
498505
pg.SYSWMEVENT,
499-
'SysWMEvent',
500-
"\n Attributes are OS-depended:\n hwnd, msg, wparam, lparam - Windows.\n event - Unix / OpenBSD\n For other OSes and in some cases for Unix / OpenBSD\n this event won't have any attributes.\n ",
506+
"SysWMEvent",
507+
"\n Attributes are OS-depended:\n hwnd, msg, wparam, lparam - Windows.\n"
508+
" event - Unix / OpenBSD\n For other OSes and in some cases for Unix / OpenBSD\n"
509+
" this event won't have any attributes.\n ",
501510
)
502-
VideoResize = _create_class(pg.VIDEORESIZE, 'VideoResize', None)
503-
VideoExpose = _create_class(pg.VIDEOEXPOSE, 'VideoExpose', None)
504-
MidiIn = _create_class(pg.MIDIIN, 'MidiIn', None)
505-
MidiOut = _create_class(pg.MIDIOUT, 'MidiOut', None)
506-
NoEvent = _create_class(pg.NOEVENT, 'NoEvent', None)
511+
VideoResize = _create_class(pg.VIDEORESIZE, "VideoResize", None)
512+
VideoExpose = _create_class(pg.VIDEOEXPOSE, "VideoExpose", None)
513+
MidiIn = _create_class(pg.MIDIIN, "MidiIn", None)
514+
MidiOut = _create_class(pg.MIDIOUT, "MidiOut", None)
515+
NoEvent = _create_class(pg.NOEVENT, "NoEvent", None)
507516
FingerMotion = _create_class(
508-
pg.FINGERMOTION, 'FingerMotion', 'Attribute "window" avalible only for SDL 2.0.14+'
517+
pg.FINGERMOTION, "FingerMotion", 'Attribute "window" avalible only for SDL 2.0.14+'
509518
)
510519
FingerDown = _create_class(
511-
pg.FINGERDOWN, 'FingerDown', 'Attribute "window" avalible only for SDL 2.0.14+'
520+
pg.FINGERDOWN, "FingerDown", 'Attribute "window" avalible only for SDL 2.0.14+'
512521
)
513522
FingerUp = _create_class(
514-
pg.FINGERUP, 'FingerUp', 'Attribute "window" avalible only for SDL 2.0.14+'
523+
pg.FINGERUP, "FingerUp", 'Attribute "window" avalible only for SDL 2.0.14+'
515524
)
516-
MultiGesture = _create_class(pg.MULTIGESTURE, 'MultiGesture', None)
517-
MouseWheel = _create_class(pg.MOUSEWHEEL, 'MouseWheel', None)
518-
TextInput = _create_class(pg.TEXTINPUT, 'TextInput', None)
519-
TextEditing = _create_class(pg.TEXTEDITING, 'TextEditing', None)
520-
DropFile = _create_class(pg.DROPFILE, 'DropFile', None)
521-
DropText = _create_class(pg.DROPTEXT, 'DropText', None)
522-
DropBegin = _create_class(pg.DROPBEGIN, 'DropBegin', None)
523-
DropComplete = _create_class(pg.DROPCOMPLETE, 'DropComplete', None)
525+
MultiGesture = _create_class(pg.MULTIGESTURE, "MultiGesture", None)
526+
MouseWheel = _create_class(pg.MOUSEWHEEL, "MouseWheel", None)
527+
TextInput = _create_class(pg.TEXTINPUT, "TextInput", None)
528+
TextEditing = _create_class(pg.TEXTEDITING, "TextEditing", None)
529+
DropFile = _create_class(pg.DROPFILE, "DropFile", None)
530+
DropText = _create_class(pg.DROPTEXT, "DropText", None)
531+
DropBegin = _create_class(pg.DROPBEGIN, "DropBegin", None)
532+
DropComplete = _create_class(pg.DROPCOMPLETE, "DropComplete", None)
524533
ControllerAxisMotion = _create_class(
525-
pg.CONTROLLERAXISMOTION, 'ControllerAxisMotion', None
534+
pg.CONTROLLERAXISMOTION, "ControllerAxisMotion", None
526535
)
527536
ControllerButtonDown = _create_class(
528-
pg.CONTROLLERBUTTONDOWN, 'ControllerButtonDown', None
537+
pg.CONTROLLERBUTTONDOWN, "ControllerButtonDown", None
529538
)
530-
ControllerButtonUp = _create_class(pg.CONTROLLERBUTTONUP, 'ControllerButtonUp', None)
539+
ControllerButtonUp = _create_class(pg.CONTROLLERBUTTONUP, "ControllerButtonUp", None)
531540
ControllerDeviceAdded = _create_class(
532-
pg.CONTROLLERDEVICEADDED, 'ControllerDeviceAdded', None
541+
pg.CONTROLLERDEVICEADDED, "ControllerDeviceAdded", None
533542
)
534543
ControllerDeviceRemoved = _create_class(
535-
pg.CONTROLLERDEVICEREMOVED, 'ControllerDeviceRemoved', None
544+
pg.CONTROLLERDEVICEREMOVED, "ControllerDeviceRemoved", None
536545
)
537546
ControllerDeviceMapped = _create_class(
538-
pg.CONTROLLERDEVICEREMAPPED, 'ControllerDeviceMapped', None
547+
pg.CONTROLLERDEVICEREMAPPED, "ControllerDeviceMapped", None
539548
)
540-
JoyDeviceAdded = _create_class(pg.JOYDEVICEADDED, 'JoyDeviceAdded', None)
541-
JoyDeviceRemoved = _create_class(pg.JOYDEVICEREMOVED, 'JoyDeviceRemoved', None)
549+
JoyDeviceAdded = _create_class(pg.JOYDEVICEADDED, "JoyDeviceAdded", None)
550+
JoyDeviceRemoved = _create_class(pg.JOYDEVICEREMOVED, "JoyDeviceRemoved", None)
542551
ControllerTouchpadDown = _create_class(
543-
pg.CONTROLLERTOUCHPADDOWN, 'ControllerTouchpadDown', 'Only for SDL 2.0.14+'
552+
pg.CONTROLLERTOUCHPADDOWN, "ControllerTouchpadDown", "Only for SDL 2.0.14+"
544553
)
545554
ControllerTouchpadMotion = _create_class(
546-
pg.CONTROLLERTOUCHPADMOTION, 'ControllerTouchpadMotion', 'Only for SDL 2.0.14+'
555+
pg.CONTROLLERTOUCHPADMOTION, "ControllerTouchpadMotion", "Only for SDL 2.0.14+"
547556
)
548557
ControllerTouchpadUp = _create_class(
549-
pg.CONTROLLERTOUCHPADUP, 'ControllerTouchpadUp', 'Only for SDL 2.0.14+'
558+
pg.CONTROLLERTOUCHPADUP, "ControllerTouchpadUp", "Only for SDL 2.0.14+"
550559
)
551560
ControllerSensorUpdate = _create_class(
552-
pg.CONTROLLERSENSORUPDATE, 'ControllerSensorUpdate', 'Only for SDL 2.0.14+'
561+
pg.CONTROLLERSENSORUPDATE, "ControllerSensorUpdate", "Only for SDL 2.0.14+"
553562
)
554-
AudioDeviceAdded = _create_class(pg.AUDIODEVICEADDED, 'AudioDeviceAdded', None)
555-
AudioDeviceRemoved = _create_class(pg.AUDIODEVICEREMOVED, 'AudioDeviceRemoved', None)
556-
RenderTargetsReset = _create_class(pg.RENDER_TARGETS_RESET, 'RenderTargetsReset', None)
557-
RenderDeviceReset = _create_class(pg.RENDER_DEVICE_RESET, 'RenderDeviceReset', None)
558-
WindowShown = _create_class(pg.WINDOWSHOWN, 'WindowShown', None)
559-
WindowHidden = _create_class(pg.WINDOWHIDDEN, 'WindowHidden', None)
560-
WindowExposed = _create_class(pg.WINDOWEXPOSED, 'WindowExposed', None)
561-
WindowMoved = _create_class(pg.WINDOWMOVED, 'WindowMoved', None)
562-
WindowResized = _create_class(pg.WINDOWRESIZED, 'WindowResized', None)
563-
WindowSizeChanged = _create_class(pg.WINDOWSIZECHANGED, 'WindowSizeChanged', None)
564-
WindowMinimized = _create_class(pg.WINDOWMINIMIZED, 'WindowMinimized', None)
565-
WindowMaximized = _create_class(pg.WINDOWMAXIMIZED, 'WindowMaximized', None)
566-
WindowRestored = _create_class(pg.WINDOWRESTORED, 'WindowRestored', None)
567-
WindowEnter = _create_class(pg.WINDOWENTER, 'WindowEnter', None)
568-
WindowLeave = _create_class(pg.WINDOWLEAVE, 'WindowLeave', None)
569-
WindowFocusGained = _create_class(pg.WINDOWFOCUSGAINED, 'WindowFocusGained', None)
570-
WindowFocusLost = _create_class(pg.WINDOWFOCUSLOST, 'WindowFocusLost', None)
571-
WindowClose = _create_class(pg.WINDOWCLOSE, 'WindowClose', None)
572-
WindowTakeFocus = _create_class(pg.WINDOWTAKEFOCUS, 'WindowTakeFocus', None)
573-
WindowHitTest = _create_class(pg.WINDOWHITTEST, 'WindowHitTest', None)
563+
AudioDeviceAdded = _create_class(pg.AUDIODEVICEADDED, "AudioDeviceAdded", None)
564+
AudioDeviceRemoved = _create_class(pg.AUDIODEVICEREMOVED, "AudioDeviceRemoved", None)
565+
RenderTargetsReset = _create_class(pg.RENDER_TARGETS_RESET, "RenderTargetsReset", None)
566+
RenderDeviceReset = _create_class(pg.RENDER_DEVICE_RESET, "RenderDeviceReset", None)
567+
WindowShown = _create_class(pg.WINDOWSHOWN, "WindowShown", None)
568+
WindowHidden = _create_class(pg.WINDOWHIDDEN, "WindowHidden", None)
569+
WindowExposed = _create_class(pg.WINDOWEXPOSED, "WindowExposed", None)
570+
WindowMoved = _create_class(pg.WINDOWMOVED, "WindowMoved", None)
571+
WindowResized = _create_class(pg.WINDOWRESIZED, "WindowResized", None)
572+
WindowSizeChanged = _create_class(pg.WINDOWSIZECHANGED, "WindowSizeChanged", None)
573+
WindowMinimized = _create_class(pg.WINDOWMINIMIZED, "WindowMinimized", None)
574+
WindowMaximized = _create_class(pg.WINDOWMAXIMIZED, "WindowMaximized", None)
575+
WindowRestored = _create_class(pg.WINDOWRESTORED, "WindowRestored", None)
576+
WindowEnter = _create_class(pg.WINDOWENTER, "WindowEnter", None)
577+
WindowLeave = _create_class(pg.WINDOWLEAVE, "WindowLeave", None)
578+
WindowFocusGained = _create_class(pg.WINDOWFOCUSGAINED, "WindowFocusGained", None)
579+
WindowFocusLost = _create_class(pg.WINDOWFOCUSLOST, "WindowFocusLost", None)
580+
WindowClose = _create_class(pg.WINDOWCLOSE, "WindowClose", None)
581+
WindowTakeFocus = _create_class(pg.WINDOWTAKEFOCUS, "WindowTakeFocus", None)
582+
WindowHitTest = _create_class(pg.WINDOWHITTEST, "WindowHitTest", None)
574583
WindowICCProfChanged = _create_class(
575-
pg.WINDOWICCPROFCHANGED, 'WindowICCProfChanged', None
584+
pg.WINDOWICCPROFCHANGED, "WindowICCProfChanged", None
576585
)
577586
WindowDisplayChanged = _create_class(
578-
pg.WINDOWDISPLAYCHANGED, 'WindowDisplayChanged', None
587+
pg.WINDOWDISPLAYCHANGED, "WindowDisplayChanged", None
579588
)
580589

581590

@@ -594,6 +603,9 @@ def __instancecheck__(self, instance: Any, /) -> bool:
594603
)
595604

596605

606+
_extra_cache[pg.USEREVENT] = UserEvent
607+
608+
597609
__all__ = [
598610
"Event",
599611
"EventType",

src_py/typing.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,9 @@ def rect(self) -> Union["RectLike", Callable[[], "RectLike"]]: ...
8181
class EventLike(Protocol):
8282
type: int
8383

84-
def __init__(self, dict: dict[str, Any] | None, **kwargs: Any) -> None: ...
84+
def __init__(
85+
self, dict: Optional[Dict[str, Any]] = None, **kwargs: Any
86+
) -> None: ...
8587

8688
@property
8789
def dict(self) -> Dict[str, Any]: ...

test/event_test.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -958,7 +958,8 @@ def test_event_class(self):
958958
self.assertIs(ev_cls, pygame.event.event_class(ev_id))
959959
self.assertEqual(ev_cls.type, ev_id)
960960

961-
for ev_id in EVENT_TYPES:
961+
for idx, ev_id in enumerate(EVENT_TYPES):
962+
print(idx, ev_id)
962963
self.assertFalse(
963964
getattr(pygame.event.event_class(ev_id), "_unknown", False)
964965
)

0 commit comments

Comments
 (0)