reloading the module imported as 'from ... import ...'

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Aug 10 08:21:36 CEST 2009


On Sun, 09 Aug 2009 22:48:31 -0700, AlF wrote:

> Steven D'Aprano wrote:
>> On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:
>> 
>>> Hi,
>>>
>>> what is the best way to reload the module imported using 'from ...
>>> import ...'
>> 
>> 
>> Have you tried "from ... import ..." again?
>> 
>> 
> I have not because of an assumption that "import" imports the module
> just once. 

Ah, of course the cached module will still reflect the older version. 
Sorry, I was thinking about solving a different problem:

- In module "main" call "from A import a"
- Some other part of your code modifies A.a
- You want to have the imported a be refreshed with the value of A.a


No, my suggestion won't help in this situation.

Instead, you can:

(1) Delete the module from sys.modules, forcing Python to re-read it from 
disk:

import sys
del sys.modules['A']
from A import a

or

(2) Recognize that Python doesn't specifically support what you're trying 
to do. reload() is a convenience function, and you probably should stick 
to the "import A; A.a" form.


-- 
Steven



More information about the Python-list mailing list