Is it appropriate to raise an EnvironmentError for os.environ? Is it appropriate to raise an EnvironmentError for os.environ? python-3.x python-3.x

Is it appropriate to raise an EnvironmentError for os.environ?


Why don't you just use

my_value = os.getenv("SOME_VALUE")

It will just return None if it doesn't exist. And if you want, you can throw your own errors.


I sense a bit of confusion as to what "EnvironmentError" is. It does not relate to environment variables. The original meaning (in Python 2) for exception EnvironmentError is:

The base class for exceptions that can occur outside the Python system: IOError, OSError.

With PEP 3151, the IO and OS exceptions were re-worked for Python 3.3, such that they all use OSError as a base class. EnvironmentVariable is kept as an alias of OSError for backwards compatibility.


Some appropriate suggestions for exceptions related to environment variables could be:

  • RuntimeError - this is a bit of a "miscellaneous" exception type, but it is perhaps appropriate if the local running environment does not have the variable set.
  • ValueError - the environment variable is set, but there is an exception with its value.