views:

71

answers:

3

When I start the interactive django shell through manage.py, by executing

python -v manage.py shell

from the project directory, I see a lot of modules of format django.package.module getting imported in the verbose output but still I have to import them to use it in the shell.

The same happens when I just run the Python shell (with the -v argument). For example I see this in the verbose output,

import os # precompiled from /usr/local/gdp/lib/python2.4/os.pyc

but still i have to do import os to import and use the os module. What is being imported that am seeing in the verbose output and why I have to import them explicitly again to use them in the shell? Does Python load some essential modules while starting the shell or is it some kind of behind-the-scene magic?

A: 

Python loads the site module implicitly when starting up, which may in turn import other modules for its own use. You can pass -S to disable this behavior.

Ignacio Vazquez-Abrams
A: 

They are getting imported (look at sys.modules) and references to the module are created in whichever modules have imported it.

When you do an import in your shell, if the module has already been imported, you will just get a copy of the reference to it in sys.modules

gnibbler
+1  A: 

-v traces the first import of a module -- the one that actually loads the module (executes its code, and so may take a bit of time) and sticks it into sys.modules.

That has nothing to do whether your interactive session (module __main__) gets the module injected into its namespace, of course. To ensure module 'goo' does get into the namespace of module 'X' (for any X, so of course including __main__... among many, many others), module 'X' just needs to import goo itself (a very fast operation indeed, if sys.modules['goo'] is already defined!-).

Alex Martelli
So what -v shows is adding the module into sys.modules and to make it available in the current module namespace it needs to be imported in the module scope. That answers my question, thanks.
Technofreak