Events in Python?

John Hunter jdhunter at ace.bsd.uchicago.edu
Wed Apr 26 12:59:45 EDT 2006


>>>>> "redefined" == redefined horizons <redefined.horizons at gmail.com> writes:

    redefined> Here is another non-pythonic question from the Java
    redefined> Developer. (I beg for forgiveness...)

    redefined> Does Python have a mechanism for events/event-driven
    redefined> programming?

The enthought traits package has built-in support for event handling,
among other things

  http://code.enthought.com/traits/

Here is an example from the web page:

from enthought.traits import Delegate, HasTraits, Int, Str, Instance 
from enthought.traits.ui import View, Item

class Parent(HasTraits):
    first_name = Str('')         # INITIALIZATION:
    last_name = Str('')          # 'first_name' and
                                 # 'last_name' are
                                 # initialized to ''
class Child(HasTraits):
    age = Int

    father = Instance(Parent)      # VALIDATION: 'father' must
                                   # be a Parent instance

    first_name = Str('')

    last_name = Delegate('father') # DELEGATION:
                                   # 'last_name' is
                                   # delegated to
                                   # father's 'last_name'

    def _age_changed(self, old, new):  # NOTIFICATION:
                                       # This method is
                                       # called when 'age'
                                       # changes
        print 'Age changed from %s to %s ' % (old, new)


  
    traits_view = View(Item(name='first_name'),   # TRAITS UI: Define
                       Item(name='last_name',     # the default window
                            style='readonly'),    # layout
                       Item(name='age'),
                       Item(name='father'))


####################################################
# Make and manipulate objects from the classes above
####################################################

joe = Parent()
joe.last_name = 'Johnson'

# DELEGATION in action
moe = Child()
moe.father = joe
print "Moe's last name is %s" % (moe.last_name)

# NOTIFICATION in action
moe.age = 10

#VISUALIZATION: Display the UI
moe.configure_traits()

The DELEGATION and NOTIFICATION segments in the above example yield
the following command-line output:

            Moe's last name is Johnson
            Age changed from 0 to 10
      



More information about the Python-list mailing list