Flutterby™! : Python tricks

Next unread comment / Catchup all unread comments User Account Info | Logout | XML/Pilot/etc versions | Long version (with comments) | Weblog archives | Site Map | | Browse Topics

Python tricks

2004-12-13 18:27:25.753492+00 by Dan Lyke 1 comments

Nerd alert, feel free to skip this. A common trick when using the Python bindings for GTK is to use the Glade library call signal_autoconnect on a map of the functions of an instance, like this:

class_methods = self.__class__.__dict__
for method_name in class_methods.keys():
method = class_methods[method_name]
if type(method) == types.FunctionType:
callbacks[method_name] = new.instancemethod(
method, self, self.__class__)

Unfortunately, this only gives the methods of the current class, not those of the superclasses. The superclass information is held in the array self.__class__.__bases__, each of which has a .__dict__ that can be iterated through similarly (and a complete solution will want to iterate through all of the parent classes). Discovering that danged .__bases__ member was a pain.

[ related topics: Python ]

comments in ascending chronological order (reverse):

#Comment Re: made: 2004-12-14 09:11:41.889761+00 by: Brian

You know, I'm almost positive that there's a much simpler way. I'm too sleepy to work it out with confidence, but a few things come to mind:

I've never mapped methods in that direction, it's always iterating over the list of signal handlers defined by the .glade file and then finding methods to bind to them. For that sort of thing, getattr(self, methname) is sufficient.

signal_autoconnect does exactly that for you. I'm pretty sure you can give it an instance instead of a mapping and it will bind the callbacks to the methods of the same names.

There are a couple of helper classes mentioned in the PyGtk FAQ that make this sort of thing even easier, something which creates a python instance for each widget on the screen and auto-connects signal handlers to methods of those instances. I forget the details, I haven't yet built something complex enough to really benefit from it, but there were multiple such frameworks floating around.

There's probably a builtin module (maybe 'inspect'?) which will do that recursive walk for you. If not I'm sure Twisted has something in twisted/python/reflect.py that would do it.

But really, I've never ever needed to know all the attributes (inherited or otherwise) of a given instance.