I thought I understood how import worked...

Laszlo Nagy gandalf at shopzeus.com
Wed Aug 8 02:40:46 EDT 2012


On 2012-08-08 06:14, Ben Finney wrote:
> Cameron Simpson <cs at zip.com.au> writes:
>
>> All of you are saying "two names for the same module", and variations
>> thereof. And that is why the doco confuses.
>>
>> I would expect less confusion if the above example were described as
>> _two_ modules, with the same source code.
> That's not true though, is it? It's the same module object with two
> different references, I thought.
They are not the same. Proof:

$ mkdir test
$ cd test
$ touch __init__.py
$ touch m.py
$ cd ..
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import sys
 >>> sys.path.append('test')
 >>> import m
 >>> from test import m
 >>> import m
 >>> from test import m as m2
 >>> m is m2
False
 >>> m.a = 3
 >>> m2.a
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'a'

So it is still true that top level code gets executed only once, when 
the module is first imported. The trick is that a module is not a file. 
It is a module object that is created from a file, with a name. If you 
change the name, then you create ("import") a new module.

You can also use the reload() function to execute module level code 
again, but it won't create a new module object. It will just update the 
contents of the very same module object:

What is more interesting is how the reload() function works:

Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import test.m
 >>> a = test.m
 >>> import os
 >>> test.m is a
True
 >>> os.system("echo \"import sys\" >> test/m.py")
0
 >>> reload(test.m) # Updates the module object
<module 'test.m' from 'test/m.py'>
 >>> test.m is a # They are still the same
True
 >>> a.sys # So a.sys is a exist
<module 'sys' (built-in)>
 >>>





More information about the Python-list mailing list