[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Adding __eq__ method to pygame Event class at runtime



Jordan Applewhite wrote:
Hi! I thought it would be nice to add an __eq__ method to the pygame.event.Event class at runtime. This would let me use == (rich comparison operator) on events in the manner of

if pygame.event.wait() == trigger_event:
   pass

I tried to do this with setattr like so (please pardon the one-liner):
setattr( pygame.event.Event.__class__, '__eq__', lambda self, other: self.type == other.type )

I've tried several variations on this idea, but the attribute seems to be off-limits. I keep getting errors like "TypeError: can't set attributes of built-in/extension type 'builtin_function_or_method'". I notice that calling pygame.event.Event.__class__ lists it as a "builtin function or method.", but I'm not sure why this means I can't create the method.

Could someone please point me in the right direction? Thanks, and I'm sorry if this is more about python than pygame. I'm hoping it passes the relevance threshold:)

You can't monkey patch `builtins` (such as C extensions) an umbrella PyGame comes under. You can not monkey patch the builtin file, str or int types either. They are `read only` Some wrappers (Boost ) work by creating a thicker layer; an actual python class which then calls the C procedures. This is more flexible in respect to monkey business with `C extensions`