I am trying to load code as a module and then reload the same module but different code programmatically in Python:
import imp
a = """
def test():
print "Hello from a"
"""
b = """
def test():
print "Hello from b"
"""
for code in [a, b]:
with open('user.py', 'wb') as f:
f.write(code)
mod = imp.load_source('user', 'user.py')
getattr(mod, "test")()
Expected output:
Hello from a
Hello from b
Actual output:
Hello from a
Hello from a
Obviously my understanding of how it works is not correct but I can't seem to figure out my mistake.
The only way I could get it to work was if I deleted the generated .pyc file before I wrote the code in the file f
. Is there a better way?