Ned Deily added the comment:
The difference is that os.environ is a reference to a mapping object,
essentially a dict, that has all of the process environment variables. By using
the get('x') method on that object, you ask the object to find and return the
value corresponding to key 'x' or to return None if the key is not found. It's
the same as using os.environ['x'] except that the latter raises a KeyError
exception if the the key is not found. This is how all mapping objects work.
(Also, os.environ() does not work because os.environ is not callable.)
os.getenv('x') is a call to the function that returns the value corresponding
to key 'x' or None. Yes, the end results of os.getenv('x') and
os.environ.get('x') are the same but how they get there is conceptually
different. Why are there two similar ways to do this? I can only speculate at
this point. It looks like os.environ and os.putenv have been around since the
very early days of Python. os.getenv appeared somewhat later but has been
around since at
least 2001 (http://bugs.python.org/issue429059). Since os.putenv already
existed, os.getenv could have been added as a convenience to mimic the
underlying libc function names. In any case, it's perfectly fine to use either
approach and has been for at least 15 years!
>>> import os
>>> os.environ()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '_Environ' object is not callable
>>> os.environ
environ({'TERM': 'xterm-256color', 'HISTCONTROL': 'erasedups', 'HOME':
'/Users/nad'})
>>> os.environ.get('HOME')
'/Users/nad'
>>> os.environ['HOME']
'/Users/nad'
>>> os.getenv
<function getenv at 0x1007318c8>
>>> os.getenv('HOME')
'/Users/nad'
----------
resolution: -> not a bug
status: open -> closed
type: resource usage ->
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue28242>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com