Is it safe to use os.environ.setdefault?

…衆ロ難τιáo~ 提交于 2019-12-04 15:37:29

问题


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?

def setdefault(self, key, failobj=None):
    if key not in self:
        self[key] = failobj
    return self[key]

Can I use this function or write a wrapper for those lines?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11047621/is-it-safe-to-use-os-environ-setdefault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!