Pro Q
Pro Q

Reputation: 5068

Python: How to update a module within the program

I have the following code in Python:

myFile = open("Test1.py", "w")
myFile.write("def foo():\n\tprint('hello world!')") #defining foo in the module Test1
myFile.close()
import Test1

Test1.foo() #this works great

myFile = open("Test1.py", "w")
#replace foo() with foo2() and a new definition
myFile.write("def foo2():\n\tprint('second hello world!')") 
myFile.close()

import Test1 #re-import to get the new functionality

Test1.foo2() #this currently throws an error since the old functionality is not replaced

I would like it if when I re-imported Test1, the functionality of foo2() replaced foo(), and the program would print "second hello world!" at the end.

The best solution I could find was to "de-import" the module, which looks potentially dangerous, and also seems unnecessary (I haven't tried it yet).

What would be the best way to get the new functionality of foo2() into the program?

Upvotes: 1

Views: 100

Answers (1)

Blair
Blair

Reputation: 6693

It seems like you would want to use the reload keyword, like so:

>>> reload(Test1)

Upvotes: 2

Related Questions