Python: raise KeyError(key) from None

This:

#!/usr/bin/env python3
import os
testing = os.environ['testing']

will generate:

Traceback (most recent call last):
  File "./my.py", line 3, in <module>
    testing = os.environ['testing']
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'testing'

if the environment variable does not exist.

 

Instead use:

testing = os.environ.get('testing', 'False')

which lets you set a default.

 

Leave a Reply

Your email address will not be published. Required fields are marked *