Is it safe to use os.environ.setdefault?

To clarify--- I had to think for a little while as to what this question and answer mean--- the Python.org docs on os.environ don't bother to mention all of the built-in methods for mapping types (such as os.environ which is basically a dictionary to which additional methods have been given).

Instead, they mainly mention the additional methods that they have given to an object in os, named environ and derived from type dict, beyond those that dict already has built in. From a book that I have on Python, the synopsis for any dictionary type is dict.setdefault(key, default=None), and the explanation is that it is similar to get() but it sets dict[key]=default if key is not already in dict.

default is perhaps not well chosen as a name here because it is easily confused with somevariablename= defaultvalue, the normal way of declaring default values in a function declaration. That is, whereas default=None certainly sets a default, it's not clear how setdefault in any sense essentially sets a default, as default may be given any value.


The os.environ documentation does state it's a mapping:

A mapping object representing the string environment.

As such it behaves according to the python mapping documentation of which dict is the standard implementation.

os.environ therefor behaves just like the standard dict, it has all the same methods:

>>> import os
>>> len(os.environ)
36
>>> 'USER' in os.environ
True
>>> os.environ.fromkeys
<bound method classobj.fromkeys of <class os._Environ at 0x107096ce8>>

The .setdefault method is documented on the same page as the rest of the mapping methods, and you can use it just fine as is.