2

Here is my code to reload a python module using the reload() build in function. I have looked at some (not all :) ) the other questions and answers in stackoverflow but to get my code to work I still need to do a os.remove('m.pyc'). Can anybody maybe explain it to me or show me how I need to change my code to make the below work without the remove.

import os

open('m.py','wt').write(r'def f(str): print "Sooo Original : %s"%(str)')
import m
m.f('Original')

os.remove('m.pyc')

open('m.py','wt').write(r'def f(str): print "Not so original : %s"%(str)')
m = reload(m)
m.f('Copy')

2 Answers 2

6

By replacing your remove statement with time.sleep(1) to prevent both files from being created nearly simultaneously, I obtain the correct result. I guess the problem is that both files have the same time stamp which prevents Python from detecting the change and truly reload the module.

Sign up to request clarification or add additional context in comments.

4 Comments

yes what you said really works, but its strange to me why python does not really import the module again when we are asking it to import it.
The pyc is a cache mechanism which is not connected to the reload mechanism. If Python does not detect the need to rebuild its cache it seems normal that import and reload will still use the same old pyc. What you need is a way to invalidate the pyc cache (that's what you do when you remove the pyc file).
As far as I know, it does go by time stamp, so another strategy would be to change m.pyc's time stamp (to a past date) rather than waiting or removing the file altogether.
Thanks. I also ended up using the time.sleep(1) approach.
0

I get a different problem on my machine.

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    m.f('Original')
AttributeError: 'module' object has no attribute 'f'

I've noticed that you didn't close your file, so it may that the contents of the file are being held in a buffer and are waiting to be written to disk. So when you come to reloading the module, python still sees the original version of the file.

From the documentation for file.write

write(...) write(str) -> None. Write string str to file.

Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.

Does the following work for you?

f = open('m.py','wt')
f.write(r'def f(str): print "Sooo Original : %s"%(str)')
f.close()

import m
m.f('Original')

f = open('m.py','wt')
f.write(r'def f(str): print "Not so original : %s"%(str)')
f.close()

m = reload(m)
m.f('Copy')

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.