instance creatiion as an "event"

Alex Martelli aleax at aleax.it
Tue Apr 22 08:32:33 EDT 2003


Arthur wrote:
   ...
> I could, of course, add self.redraw() to TestPoint.__init__.  But it
> seems, because of the overall "real world" design where TestPoint is
> somewhere down an inheritance chain, I need to call this explicitly on the
> top level class - and need to do some restructuring of the inheritance

I don't understand this.  When you call:

    p = TestPoint(args)
    p.redraw()

it's EXACTLY AS IF TestPoint.__init__'s very last statement was

    self.redraw()

and I don't see any way the latter can fail to do exactly the same
job as the former.  It cannot matter how deeply nested in whatever
inheritance DAG class TestPoint might be.


However, if you did put self.redraw() in TestPoint.__init__, then
the redraw would occur WHENEVER a TestPoint instance is created,
be that "interactively", or otherwise.

> Being stumped there, and lazy, I was looking for some interactive magic.
> so that p1=TestPoint(1,2) would somehow register as an event calling
> draw_all().

You could make the redraw conditional on module sys having an
attribute named 'ps1' -- that's what, I think, is normally used
to check whether one is in an interactive session, or not.  Still,
that wouldn't tell you if a SPECIFIC call was "at the interactive
prompt".

You could help by avoiding the from-star-import idiom and
doing instead some trick to ensure that the callables in your
module are wrapped (by wrappers of the same name) for use
at the interactive-prompt only (i.e. in module __main__ iff
you're in an interactive session).  E.g. at the end of your
module's code you might have [warning, untested code!]:

if __name__ == '__main__':
    "normal run-as-script code here"
else:
    import sys
    if hasattr(sys, 'ps1'):
        import __main__
        def makewrapper(func):
            def wrapper(*args, **kwds):
                result = func(*args, **kwds)
                draw_all()
                return resukt
            return wrapper
        for name, value in vars():
            if callable(value):
                setattr(__main__,name,makewrapper(value))

or something like that.  If you do this sort of thing often
you could factor it out into an helper module, of course.


Alex





More information about the Python-list mailing list