Skip to content

Instantly share code, notes, and snippets.

@onelharrison
Created December 17, 2020 22:43
Show Gist options
  • Save onelharrison/f3dc388ec00d52efb378191f6d5def6f to your computer and use it in GitHub Desktop.
Save onelharrison/f3dc388ec00d52efb378191f6d5def6f to your computer and use it in GitHub Desktop.
Implementation of a safe get function in Python
def safe_get(collection, key, default=None):
"""Get values from a collection without raising errors"""
try:
return collection.get(key, default)
except TypeError:
pass
try:
return collection[key]
except (IndexError, TypeError):
pass
return default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment