Yuxiang Wang
Yuxiang Wang

Reputation: 8433

Python module import : what about modules imported in the imported module

Sorry about putting this probably naive question. I tried to look for doc and do some experiments, but I wanted to make sure that this is the case:

If, in file test.py, I had:

import module1

And I do this in console:

import test

I would not import the module1 in the console.

And if I do this:

from test import *

Also, module1 would not be imported into the console.

Is that correct? Thanks!

Upvotes: 0

Views: 56

Answers (2)

user2357112
user2357112

Reputation: 281949

import test

This only imports the name test into the current namespace. Anything in test's namespace is accessible as test.whatever; in particular, module1 is available as test.module1, though you shouldn't use that.

from test import *

This imports everything that doesn't start with an underscore from test's namespace into the current one. Since module1 is available in test's namespace, this does import the name module1.

Upvotes: 3

Phillip Cloud
Phillip Cloud

Reputation: 25692

Your experiment can be conducted very easily from the shell:

╭─phillip@phillip-laptop  ~ ‹ruby-1.9.3@global› ‹pandas›
╰─$ echo "import module1" > test.py
╭─phillip@phillip-laptop  ~ ‹ruby-1.9.3@global› ‹pandas›
╰─$ touch module1.py
╭─phillip@phillip-laptop  ~ ‹ruby-1.9.3@global› ‹pandas›
╰─$ py
Python 2.7.5 (default, May 17 2013, 07:55:04)
[GCC 4.8.0 20130502 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.module1
<module 'module1' from 'module1.py'>
>>> from test import *
>>> module1
<module 'module1' from 'module1.py'>

Upvotes: 0

Related Questions