Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you reference modules that appear to be automatically loaded by the interpreter without an additional `import` statement?

When you start your Python interpreter it appears that some modules/packages are automatically imported during the startup process:

python
Python 2.7.6 (default, Jan 13 2014, 14:59:37)
...
>>> import sys
>>> for key in sys.modules.iterkeys():
...     print(key)
...
os
sys
abc
others ...

However, these modules seem to have been loaded into a different scope/namespace because you can't access them without an additional import:

>>> abc
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined

Here are my questions:

  1. What precisely is loading these modules and for what purpose?
  2. What scope/namespace were they loaded into?
like image 332
eikonomega Avatar asked May 28 '15 22:05

eikonomega


1 Answers

the sys module is loading them into the sys.modules dictionary namespace

if you wanted to I guess you could access them as

abc = sys.modules["abc"]

but not sure why you would want to

like image 119
Joran Beasley Avatar answered Sep 28 '22 08:09

Joran Beasley