0

How can I reload an imported file with python ?

def ClickOpenMyFile(self):
    import myfileinquestion

I want that unimport and import back if was already imported...

It is supposded to work ? No error but don't work for me

try:
    import myfile
except:
    reload(myfile)
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
Tiziano Dan
  • 81
  • 1
  • 2
  • 5

2 Answers2

0

Ok, a real unload is not existing in Python. (as Vladimir already mentioned)

Assume you have a file foo.py with the following content:

NAME = "MyName"
def foo_funct():
    print "foo.foo_funct called", NAME

Importing and reloding works fine:

>>> import foo
>>> foo.foo_funct()
foo.foo_funct called MyName
>>> foo.NAME = "ANewName"
>>> foo.foo_funct()
foo.foo_funct called ANewName
>>> reload( foo )
<module 'foo' from 'foo.pyc'>
>>> foo.foo_funct()
foo.foo_funct called MyName

If I understood you right, this is what you want:

try:
    reload(foo)
except NameError:
    import foo

reload will fail with a NameError if foo is not already imported. So catch this one and execute a normal import then.

Robert Caspary
  • 1,584
  • 9
  • 7
0

First of all, there are plenty of similar questions. For example this one: How do I unload (reload) a Python module?

There is no general way to track any changes in already loaded modules; you might want to track any chages by your own. However there are some modules available that perform reload if source code was changed. In some cases tornado.autoreload may be useful for you.

Community
  • 1
  • 1
Vladimir
  • 9,913
  • 4
  • 26
  • 37