[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] dynamic pygame programming



On, Wed Nov 07, 2007, Lionel Barret De Nazaris wrote:

> Hi all,
> I am considering using pygame for a new prototype and I wonder if any of
> you has any experience with what I call dynamic programming.
> 
> Basically, I want to launch  Ipython,  import the main module of the
> program, run it , then, pause it, modify any module and having them
> reloaded and relinked.
> All this without restarting the program.
> 
> Would that be possible ? if so how ?
> 
> It's very smalltalkish, but i wonder if it is possible in Python....
> 

Yes it is (with more or less effort). You baically can rebind anything
in Python as you have no strict separation between modules, functions,
methods, attributes, classes and objects (basically anything is an
object).

Let's say we've got a module foo, which looks like this:

Content of foo.py:

    def func1 ():
        print "This is foo.func1"

    def func2 ():
        print "This is foo.func2"

The module initialization file __init__.py gives us:

    from foo import *

Your code using module foo now will rebind foo's func1 function:

    import foo

    def rebind ():
        print "This is not foo.func1 anymore"

    foo.func1 = rebind
    foo.func1 ()

This works fine for local (file) scopes, but outside of them you
probably won't notice it. Once the changes are written back to the
module, the reload() function can be used to 'reimport' the module
within the affected files:

    import foo

    # ...

    def notify_reload ():
        # Module was changed somewhere, force a reload.
        reload (foo)

However, reload() will not work together with the 'from x import y'
imports as those bind the module's imported stuff directly within the
local scope. Thus such things have to be avoided in order to support the
dynamic rebinding of the module symbols.

Regards
Marcus

Attachment: pgpWOBRe01TKV.pgp
Description: PGP signature