[Tutor] Callbacks in a python module

dman dman@dman.ddts.net
Wed, 15 May 2002 10:10:53 -0500


--Xm/fll+QQv+hsKip
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On Tue, May 14, 2002 at 11:41:52PM -0500, Nate Custer wrote:
| Hey all,
|=20
| I like using callbacks in my pygtk programs, is there any way a python
| module can do the same thing? Specificly I need a class in one module to
| call a fcn in a different module.
|=20
| Here is the object tree:
|=20
| tn5250py
|  \
|   |-lib5250
|   |   \
|   |    |-called from here
|   |
|   |-5250gui=09
|       \
|        |- here is screen refesh method.

I think you're trying to recreate Legacy Integrator (see
http://www.redoaksw.com) in python.
=20
| What is the best way to do this?

I'll give an example that follows the Observer Patter[1]

class Observable :
    def __init__( self ) :
        self._listeners =3D []

    def add_listener( self , func ) :
        """
        this is where we give it a "callback"
        """
        self._listeners.append( func )

    def notify_listeners( self ) :
        """
        this is where we actually call back
        """
        for f in self._listeners :
            f()

# here is a function we want to have called by an "observable" object
def our_callback() :
    print "Yea!"

obj =3D Observable()
obj.add_listener( our_callback )
# normally this next line would be somewhere else in the program
obj.notify_listeners()


-D


[1] See "Design Patterns" by the Gang Of Four

--=20

A wise servant will rule over a disgraceful son,
and will share the inheritance as one of the brothers.
        Proverbs 17:2
=20
GnuPG key : http://dman.ddts.net/~dman/public_key.gpg


--Xm/fll+QQv+hsKip
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iEYEARECAAYFAjzien0ACgkQO8l8XBKTpRTg8gCdGE8vOkz53WzhQzPlktAEmKnA
meUAoItMGFrtDqB2etXw9r3RgmC5ONP0
=AGZe
-----END PGP SIGNATURE-----

--Xm/fll+QQv+hsKip--