Python

Python

Made by DeepSource

Shallow copy of os.environ detected PYL-W1507

Bug risk
Major
Autofix

os.environ is not a dict but proxy object. The use of copy.copy(os.environ) will make a shallow copy of os.environ therefore, any changes made in the copy would be reflected in os.environ as well. It is recommended to use os.environ.copy() instead. See https://bugs.python.org/issue15373 for reference.

>>> # Making a copy of the environment variables using `copy.copy`
>>> shallow_copy = copy.copy(os.environ)
>>>
>>> # Fetching value for a non-existent key from `os.environ`
>>> os.environ.get("test-1", "Not found")
'Not found'
>>>
>>> # Adding this in the shallow copy:
>>> shallow_copy["test-1"] = "This was added in the copy of os.environ"
>>>
>>> # Query os.environ for the key again:
>>> os.environ.get("test-1", "Not found")
'This was added in the copy of os.environ'
>>>
>>> # Using os.environ.copy() directly:
>>> deep_copy = os.environ.copy()
>>>
>>> # Fetching value for a non-existent key from `os.environ`
>>> os.environ.get("test-2", "Not found")
'Not found'
>>>
>>> # Adding this in the deep_copy:
>>> deep_copy["test-2"] = "This was added in the copy of os.environ"
>>>
>>> # Query os.environ for the key again:
>>> os.environ.get("test-2", "Not found")
'Not found'