Home > database >  How does CPython implement os.environ?
How does CPython implement os.environ?

Time:03-31

I was looking through source and noticed that it references a variable environ in methods before its defined:

def _createenviron():
    if name == 'nt':
        # Where Env Var Names Must Be UPPERCASE
        def check_str(value):
            if not isinstance(value, str):
                raise TypeError("str expected, not %s" % type(value).__name__)
            return value
        encode = check_str
        decode = str
        def encodekey(key):
            return encode(key).upper()
        data = {}
        for key, value in environ.items():
            data[encodekey(key)] = value
    else:
        # Where Env Var Names Can Be Mixed Case
        encoding = sys.getfilesystemencoding()
        def encode(value):
            if not isinstance(value, str):
                raise TypeError("str expected, not %s" % type(value).__name__)
            return value.encode(encoding, 'surrogateescape')
        def decode(value):
            return value.decode(encoding, 'surrogateescape')
        encodekey = encode
        data = environ
    return _Environ(data,
        encodekey, decode,
        encode, decode)

# unicode environ
environ = _createenviron()
del _createenviron

So how does environ get setup? I cant seem to reason about where its initialized and declared so that _createenviron can use it?

CodePudding user response:

TLDR search for from posix import * in os module content.

The os module imports all public symbols from posix (Unix) or nt (Windows) low-level module at the beginning of os.py.

posix exposes environ as a plain Python dict. os wraps it with _Environ dict-like object that updates environment variables on _Environ items changing.

  • Related