Strange behavior when importing modules

I have a Python package called simply a "package". In it, I have an empty __init__.py and two modules. One is called m1.py and contains only one line:

 x = 3 

Another is called m2.py and contains the following line:

 x = 5 

Now I am trying to use these modules. At first I do something like this:

 from package.m1 import x print package.m1.x 

Of course, this will not work - I get this error:

 NameError: name 'package' is not defined 

And I understand why this is not working. But then I do something like this:

 from package.m1 import x import package.m2 print package.m1.x 

And now it works. What for? How? I did not import package.m1!

+4
source share
2 answers

I have only one explanation:

  • from package.m1 import x loads the modules package and package.m1 . m1 added to the package module, but package not added to your global variables.
  • import package.m2 now adds the package module to your global variables. Since m1 already part of package , it is now available through package.m1 .

Further testing:

 >>> from package import m1 >>> package.m1 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'package' is not defined >>> import package.m2 >>> package.m1 <module 'package.m1' from 'package/m1.py'> >>> from package import m3 >>> package.m3 <module 'package.m3' from 'package/m3.py'> 

Testing continued:

 >>> import package.m1 >>> del package >>> import package >>> package.m1 <module 'package.m1' from 'package/m1.py'> 
+2
source

The syntax from x import y imports the entire module, and then refers to the specified object in the current namespace. It can be translated as:

 import x y = xy 

So you are actually importing package.m1

0
source

All Articles