views:

81

answers:

2

Using this code, many keys are output, but I expected no output:

import os

for i in os.environ:
    print  i

This is the code from os.py:

try:
    environ
except NameError:
    environ = {}

Where does os.environ get its values from? Where is it initialized?

+6  A: 

The os module starts by importing all names from a platform-specific submodule (such as _nt or _posix) then does a little normalization. Clearly the environ name (standing for the system environment) was defined by the platform-specific submodule (as it's normally expected to be!!!), so the except clause in os.py didn't trigger and os.environ is just the rich dictionary it's normally supposed to be.

Alex Martelli
+4  A: 

The quoted code from os.py is a backstop. It's saying, if no-one has yet defined an environ variable, create one, with an empty dictionary as a value.

But environ does exist, because it has been imported by this further up on line 58:

from nt import *

if you're running Windows, and similar platform-specific imports for other platforms. So in practice environ will always exist and the empty dict backstop will never be used.

Why bother provide a backstop then? Well, it's of dubious usefulness in the real world since as far as I can see all the platforms currently supported by the core Python distribution do implement a proper environ lookup. However there may be, or have been, unusual platforms where Python runs that do not have environment variables, and it may be of use when developing a new platform not to have a lot of programs fail to run when system interfaces like environment variables are not written yet.

bobince