what is the best way to reload the module imported using 'from ... import ...'
Is following a way to do so?
>>> from email.charset import Charset >>> reload(email.charset) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'email' is not defined >>> >>> >>> import email.charset >>> reload(email.charset) <module 'email.charset' from '/usr/lib/python2.5/email/chars
Probably it works but I do not like it as I end up with two namespaces for the symbol Charset: email.charset.Charset and Charset
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 D'Aprano <ste...@REMOVE.THIS.cybersource.com.au> (SD) wrote: >SD> 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. >SD> Ah, of course the cached module will still reflect the older version. >SD> Sorry, I was thinking about solving a different problem:
If you do a reload in between the cached version is replaced by the new version. However, objects from the old module that have references before the reload will still lie around. This could cause very subtle bugs.
Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information.
>>> import testmod >>> from testmod import TestClass >>> a = TestClass() >>> b = TestClass() >>> a.__class__ is b.__class__ True >>> reload(testmod)
<module 'testmod' from 'testmod.pyc'>
>>> c = TestClass() >>> c.__class__ is a.__class__ True >>> from testmod import TestClass >>> d = TestClass() >>> d.__class__ is a.__class__