[issue20658] os.environ.clear() fails with empty keys (posix.unsetenv)

STINNER Victor report at bugs.python.org
Mon Aug 30 10:22:24 EDT 2021


STINNER Victor <vstinner at python.org> added the comment:

The following command still fails on the Python main branch on Linux:
---
$ env -i =value ./python -c 'import pprint, os; pprint.pprint(os.environ); del os.environ[""]'
environ({'': 'value', 'LC_CTYPE': 'C.UTF-8'})
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/home/vstinner/python/main/Lib/os.py", line 689, in __delitem__
    unsetenv(encodedkey)
    ^^^^^^^^^^^^^^^^^^^^
OSError: [Errno 22] Invalid argument
---

'del os.environ[""]' calls unsetenv("") which fails with EINVAL.

Python is a thin wrapper to C functions setenv() and unsetenv(), and raises an exception when a C function fails. It works as expected.

Python exposes the variable with an empty name which is found in the environment variables: again, it works as expected.

I don't see how Python could do better, since the glibc unsetenv() fails with EINVAL if the string is empty. It is even a documented behaviour, see the unsetenv() manual page:
---
ERRORS

   EINVAL name is NULL, points to a string of length 0, or contains an '=' character.
---

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue20658>
_______________________________________


More information about the Python-bugs-list mailing list