Extending program with imported user code.

Ian Sparks ians at etrials.com
Fri Jan 17 13:35:29 EST 2003


Ok, so I RTFM and in case it helps anyone in future this is the simplistic example code I came up with :

=== test1.py ====

def test():
    print "test 1 x = %d " % x

if __name__ == "__main__":

    x = 1
    execfile('test2.py') 
    test()

=== test2.py ====

def test():
    print "test 2 x= %d" % x


when I run this the result I get is :

test 2 x= 1

i.e. the methods defined in test2.py override the methods in test1.py and have access to the namespace (because I didn't define a namespace in execfile).

Its a system wide-open to abuse because you can override any method in test1.py with a new method in test2.py but it is perfect for my in-house use. Now I can customize any feature of my program via an external file without having to touch the main program.



-----Original Message-----
From: Ian Sparks 
Sent: Thursday, January 16, 2003 12:04 PM
To: Python-List at Python. Org (E-mail)
Subject: Extending program with imported user code.


I have a python (2.2) program that does PDF rendering (www.reportlab.com). It has a method something like :

def drawfooter(..):
    blah....

I'd like to be able to override this default behaviour by importing user-defined code. So I'd envison that my user would write a replacement drawfooter() function with the same signature in a text file, my code will look for that file and import it somehow to override the existing behaviour.

What would be the best way of going about this kind of dynamic function-replacement?


-- 
http://mail.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list