events/callbacks - best practices

anton muhin antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Tue Oct 14 09:06:24 EDT 2003


HankC wrote:
> Greetings:
> 
> I'm been programming Delphi for a while and am trying to get into the
> Python mindset.  In Delphi, you can have a component class that has
> properties, methods, and events.  Properties and methods translate
> pretty easily to Python but I'm not sure about the best way to handle
> events.  For example, from fxn retrbinary in ftplib there is:
> 
>         while 1:
>             data = conn.recv(blocksize)
>             if not data:
>                 break
>             callback(data)
>         conn.close()
>  
> In delphi this would be something like:
> 
>         while 1:
>             data = conn.recv(blocksize)
>             if not data:
>                 break
>             if assigned(OnProgress) then    
>                 callback(data)
>         conn.close()
>  
> In other words, the class can handle a number of events but passing a
> callback function is not mandatory.  If you want to handle an event,
> it is assigned and dealt with.
> 
> I'm especially interested in non-visual components (like the ftplib)
> and the examples I can find all deal with the events of visual
> components that interjects more complexity than I'd like at this stage
> of my knowledge.
> 
> My goal is to rewrite a number of non visual components in Python.
> What I'd like to find is a 'non visual component design in Python'
> guide somewhere.  So...  I'm more than willing to study if I can find
> the resources - if you have any please lay them on me!  Part of my
> problem, I'm sure, is poor terminology use.
> 
> Of course, any general comments are welcomed - I'm not really
> expecting a tutorial here, though :-)
> 
> Thanks!

It's not clear what precisely you are looking for, but just some ideas:

class Foo(object):
     def __init__(self):
         self.__callback = None

     def set_callback(self, callback):
         self.__callback = callback

     def fire(self, *args, **kw):
         if self.__callback:
             return self.__callback(*args, **kw)
         else:
             return self.default_callback(*args, **kw)

     def default_callback(self, *args, **kw):
         return "default_callback(%s, %s)" % (args, kw)

foo = Foo()
print foo.fire("me", bar = "oops")

def callback(*args, **kw):
     return "callback(%s, %s)" % (args, kw)

foo.set_callback(callback)
print foo.fire("you", oops = "foo")


Properties may be even fancier. __call__ method might be useful too.

hth,
anton.





More information about the Python-list mailing list