Is it safe to use os.environ.setdefault?

前端 未结 2 1856
不知归路
不知归路 2021-02-05 05:12

From my ipython shell, I see a method setdefault in os.environ but it is not documented. http://docs.python.org/library/os.html#os.environ. Is it documented somewhere else?

相关标签:
2条回答
  • 2021-02-05 06:06

    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.

    0 讨论(0)
  • 2021-02-05 06:15

    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.

    0 讨论(0)
提交回复
热议问题