implementing callback function

Steve Holden steve at holdenweb.com
Thu May 31 20:21:37 EDT 2007


Ron Provost wrote:
> Within an application I'm working on.  The app is written in multiple 
> layers such that lower layers provided services to higher layers.  
> Ideally in such an architecture, the high-level objects know about 
> lower-level ones, but lower-level objects know nothing about the 
> higher-level ones.  There's only one problem.  When this software was 
> originally wirtten, one of the low-level objects was given knowledge of 
> a higher-level object.  This creates a really ugly dependency that I 
> want to eliminate.
>  
> My solution (at least what I'm trying to implement) is a classic one.  
> When a low-level routine needs info from a higher-level routine, let the 
> higher-level routine provide a callback which the lower-level routine 
> can call.  In this way, the lower-level routine knows nothing about 
> higher-level routines.
>  
> However, Python is complaining about my implementation.  It raises an 
> exception:  TypeError: unbound method fn_impl() must be called with X 
> instance as first argument (got int instance instead)
>  
> For simplicity, I've narrowed it down to a bit of sample code.  class X 
> is my low-level service.
>  
> class X( object ):
>    fn = None
>  
>    @staticmethod
>    def callX( n ):
>       return X.fn( n )
>  
>  
> Now, the following global stuff represents my higher-level routines:
>  
> def fn_impl( n ):   # my callback
>    return n + 1
>  
> X.fn = fn_impl      # register my callback
>  
> Now I can do something which forces my callback (fn_impl) to get called
>  
> print X.callX( 3 )
>  
>  
> I think I would get '4' printed but instead get the above error.  What 
> am I doing wrong?
>  
Normally the callback would be an instance variable, not a class 
variable, so each instance could have its own callback. Why use a class 
at all if all instances use the same callback? So I don't really 
understand why callX is a static method either.

How about (untested):

class X(object):

   def __init__(self, callback):
     self.callback = callback

   def callX(self, n):
     return self.callback(n)

def fn_impl(n):
   return n+1

x = X(fn_impl)

print x.callX(3)

If I'm right, you should see 4 if you paste this into an interpreter.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
------------------ Asciimercial ---------------------
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.com        squidoo.com/pythonology
tagged items:         del.icio.us/steve.holden/python
All these services currently offer free registration!
-------------- Thank You for Reading ----------------




More information about the Python-list mailing list