Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's imp.reload() function is not working?

Tags:

python

import

Here's a concise example:

x.py:

class x:
  var = 'from x.py'

y.py:

class x:
  var = 'from y.py'

test.py

import imp
def write_module(filename):
  fp = open('z.py', 'w')
  fp.write(open(filename).read())
  fp.close()

write_module('x.py')
import z
print(z.x.var) # Prints 'from x.py'
write_module('y.py')
imp.reload(z)
print(z.x.var) # Prints 'from x.py'

I'm not sure why both print statements are the same. How can I make python use the new definition of class x after reload()?

like image 374
Scott Frazer Avatar asked Nov 14 '11 14:11

Scott Frazer


1 Answers

This happens because the file creation dates (of z.py and its compiled counterpart z.pyc) are identical, so Python thinks that the file is unchanged and doesn't recompile it.

Actually, when I was trying and re-trying your code, it once worked as expected - probably because the two files happened to be created on either side of the system clock's second-changeover.

import imp
import time
def write_module(filename):
  fp = open('z.py', 'w')
  fp.write(open(filename).read())
  fp.close()

write_module('x.py')
import z
print(z.x.var) # Prints 'from x.py'
time.sleep(1)  # Wait one second
write_module('y.py')
imp.reload(z)
print(z.x.var) # Prints 'from y.py'

shows the expected result.

like image 124
Tim Pietzcker Avatar answered Sep 24 '22 00:09

Tim Pietzcker