How to modify a program while it's running?

Aaron Brady castironpi at
Wed Dec 17 02:36:22 CET 2008

On Dec 16, 7:26 pm, Steven D'Aprano <st... at REMOVE-THIS-> wrote:
> On Tue, 16 Dec 2008 13:25:17 -0700, Joe Strout wrote:
> > So I'd like to restructure my app so that it can stay running and stay
> > logged in, yet I can still update and reload at least most of the code.
> > But I'm not sure what's the best way to do this.  Should I move the
> > reloadable code into its own module, and then when I give my bot a
> > "reload" command, have it call reload on that module?  Will that work,
> > and is there a better way?
> That should work for functions, but less successfully with classes. The
> problem is that existing objects will still have the old behaviour even
> after reloading the class.

Good catch, Mr. Steven.  You could re-query on every call to a method
with __getattr__.

def __getattr__( I, name ):
  cls= module.class_to_query
  return cls.__getattr__( I, name ) #need to call __get__ on this

That way, when 'class_to_query' changes, the behavior changes.

Here's the implementation:

>>> class Behavior( object ):
...     def methA( I ):
...             print 'methA one'
>>> class Dynamic( object ):
...     def __getattr__( I, key ):
...             return getattr( Behavior, key ).__get__( I, Behavior )
>>> x= Dynamic( )
>>> x.methA( )
methA one
>>> class Behavior( object ):
...     def methA( I ):
...             print 'methA two'
>>> x.methA( )
methA two

You would have to soft-code 'Behavior' into the initializer of
'Dynamic' as a string, not the class object.

More information about the Python-list mailing list