Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to use os.environ.setdefault?

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?

like image 464
balki Avatar asked Jun 15 '12 09:06

balki


People also ask

What does OS environ get do?

For that, there's os. environ. get(). This retrieves the value of an environment variable currently set on your system.

Can python set environment variables?

With python code, environment variables can be set and manipulated. Setting the environment variable with code makes it more secure and it does not affect the running python script.

What are environment variables in python?

Environment variables are variables you store outside of your program that can affect how it runs. For example, you can set environment variables that contain the key and secret for an API. Your program might then use those variables when it connects to the API.


1 Answers

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.

like image 153
Martijn Pieters Avatar answered Sep 22 '22 23:09

Martijn Pieters