Python Import Statements – Differences Between Various Import Statements in Python

importpythonpython-2.7

import sys
from sys import argv

I read about about import statement in pydocs. It says it executes in two steps. (1)find a module, and initialize it if necessary; (2) define a name or names in the local namespace (of the scope where the import statement occurs). The first form (without from) repeats these steps for each identifier in the list. The form with from performs step (1) once, and then performs step (2) repeatedly.

Here I understood that in first case sys module will be initialized as part of 1st step and then it will be made available to local namespace as 2nd step.
But what will happen in case of second import form?
Will sys module be initialized as first step and only argv function of sys module(NO OTHER function) is made available to local namespace.
Because I am not able to call any other functions of sys module when I am using second form of import statement. So just want to clarify on it specifically. As if sys module has been initialized in from import statement then we should be able to call other functions using sys. But that is not working.

#import sys
from sys import argv

script, input = argv

print "This was the input entered by command line", input

print sys.path # this is not working giving error name sys is not defined.

I am suspecting in case of from import statement sys module is not getting initalized, only argv function is getting initialized but in that case what does from step performs step(1) once mean pydocs?(Note: I am working on python 2.7)

Best Answer

The import statement always initializes the whole module. The modules are stored in the sys.modules dictionary.

When you use from sys import argv the sys module is not bound locally, only argv is. You cannot use the name sys in your module, because you didn't import that name.

You can only reach the sys module if you imported sys separately:

from sys import argv

script, input = argv

import sys
print sys.path

And you can always access all imported modules by accessing sys.modules:

from sys import modules

print modules['sys'].path

Here I bound the name modules to the sys.modules dictionary, and through that reference, find the sys module, and reference the path attribute.

Demo:

>>> from sys import modules
>>> modules['sys']
<module 'sys' (built-in)>
>>> sys
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'sys' is not defined
Related Question