weakref pitfall

O

Odalrick

I'm trying to write a simple game and decided I need an eventmanager.

<code>
import weakref
from collections import defaultdict

class _EventManager( object ):
def __init__( self ):
self._handled_events =
defaultdict( weakref.WeakKeyDictionary )

def register( self, handler, event_type, filter=None ):
self._handled_events[event_type][handler] = filter

def deregister( self, handler, event_type ):
self._handled_events[event_type].pop( handler, None )

def handle_event( self, event ):
event_type = event.type
for handler, filter in
self._handled_events[event_type].items():
if filter == None or filter(event):
handler( event )

eventmanager = _EventManager()

__all__ = [ eventmanager ]
</code>

Fairly simple, yet there was some strange bug that prevented my game
from exiting.

I think what happened was that when __init__ ends, self goes out of
scope, and by extension so does self.handle_quit, Now there are no
more refeences to self.handle_quit, because weakrefs don't count, and
the event gets automatically dropped from my eventmanager. I thought
that wouldn't happen because handle_quit is part of the class and
instance MainGame.

Am I right in my guess? If so, how should I adress this bug? If not,
what is the bug?

<code>
import pygame
from eventmanager import eventmanager

class MainGame( object ):
def __init__( self, width=1024, height=768 ):
#Initialize PyGame
pygame.init()
self.width = width
self.height = height
self.quit_game = False
#Create the Screen
self.screen = pygame.display.set_mode( ( self.width,
self.height ) )
eventmanager.register( self.handle_quit, pygame.QUIT )
eventmanager.register( self.handle_quit, pygame.KEYDOWN,
key_filter( pygame.K_ESCAPE ) )

def mainloop( self ):
handle_event = eventmanager.handle_event
self.quit_game = False
while not self.quit_game:
for event in pygame.event.get():
handle_event( event )

def handle_quit( self, event=None ):
self.quit_game = True

def key_filter( key ):
def filter( event ):
return event.key == key
return filter

def handle_print_event( event ):
print str( event )

if __name__ == "__main__":
game = MainGame()
game.mainloop()
</code>
 
P

Paul Hankin

I'm trying to write a simple game and decided I need an eventmanager.

<code>
import weakref
from collections import defaultdict

class _EventManager( object ):
def __init__( self ):
self._handled_events =
defaultdict( weakref.WeakKeyDictionary )

def register( self, handler, event_type, filter=None ):
self._handled_events[event_type][handler] = filter

def deregister( self, handler, event_type ):
self._handled_events[event_type].pop( handler, None )

def handle_event( self, event ):
event_type = event.type
for handler, filter in
self._handled_events[event_type].items():
if filter == None or filter(event):
handler( event )

eventmanager = _EventManager()

__all__ = [ eventmanager ]
</code>

Fairly simple, yet there was some strange bug that prevented my game
from exiting.

I think what happened was that when __init__ ends, self goes out of
scope, and by extension so does self.handle_quit, Now there are no
more refeences to self.handle_quit, because weakrefs don't count, and
the event gets automatically dropped from my eventmanager. I thought
that wouldn't happen because handle_quit is part of the class and
instance MainGame.

Am I right in my guess? If so, how should I adress this bug? If not,
what is the bug?

The next stage in debugging is to think of a test that will prove your
guess right or wrong. I'd remove weakrefs from your event manager and
see if your code starts working.

I'd suggest you're a bit confused about your event manager's API: you
have register/deregister methods and are also using weakrefs to
provide auto-deregistering. I don't know your code, but this looks
like a mistake to me - can you justify (to yourself) that you need
both ways?
 
O

Odalrick

The next stage in debugging is to think of a test that will prove your
guess right or wrong. I'd remove weakrefs from your event manager and
see if your code starts working.

I'd suggest you're a bit confused about your event manager's API: you
have register/deregister methods and are also using weakrefs to
provide auto-deregistering. I don't know your code, but this looks
like a mistake to me - can you justify (to yourself) that you need
both ways?

Yes, I did a test with a standard dict and that removed the bug,
should have mentioned that.

And, no, I'm not sure I need both. Currently I'm using the standard
dict.

I'm fairly sure I'll need to manually deregister sometimes, buttons
and whatnot, but automatic deregistration sounds nice for later when
I'll have hundreds of sprites flying around.
 
P

Peter Otten

Odalrick said:
I'm trying to write a simple game and decided I need an eventmanager.

<code>
import weakref
from collections import defaultdict

class _EventManager( object ):
def __init__( self ):
self._handled_events =
defaultdict( weakref.WeakKeyDictionary )

def register( self, handler, event_type, filter=None ):
self._handled_events[event_type][handler] = filter

def deregister( self, handler, event_type ):
self._handled_events[event_type].pop( handler, None )

def handle_event( self, event ):
event_type = event.type
for handler, filter in
self._handled_events[event_type].items():
if filter == None or filter(event):
handler( event )

eventmanager = _EventManager()

__all__ = [ eventmanager ]
</code>

Fairly simple, yet there was some strange bug that prevented my game
from exiting.

I think what happened was that when __init__ ends, self goes out of
scope, and by extension so does self.handle_quit, Now there are no
more refeences to self.handle_quit, because weakrefs don't count, and
the event gets automatically dropped from my eventmanager. I thought
that wouldn't happen because handle_quit is part of the class and
instance MainGame.

No, self is yet another reference to the _EventManager instance which
survives the __init__() call because it is also referenced by the
global variable eventmanager.
On the other hand, self.handle_quit creates a new bound-method object every
time which doesn't even live as long as __init__().
Am I right in my guess? If so, how should I adress this bug? If not,
what is the bug?

The easiest option, to forget about weakrefs, seems to be the best
here. The other option is to keep a reference to the bound method, e. g.:

class MainGame(object):
def __init__(self, ...):
# put a bound method into the MainGame instance
# you can use a different attribute name if you want
hq = self.handle_quit = self.handle_quit
# register it
eventmanager.register(hq, ...)

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top