Skip to content

Instantly share code, notes, and snippets.

@odedlaz
Last active January 20, 2017 15:23
Show Gist options
  • Select an option

  • Save odedlaz/ce10ccd1942bf808446128e57b11d768 to your computer and use it in GitHub Desktop.

Select an option

Save odedlaz/ce10ccd1942bf808446128e57b11d768 to your computer and use it in GitHub Desktop.
os.getenv idiom
import os
def getenv(varname, default=None, typecast_fn=None):
"""
Return the value of the environment variable varname if it exists, or default if it doesn't.
default defaults to None.
:typecast_fn: a function that performs the typecast. if not supplied, defaults to type(value)
"""
if not typecast_fn:
typecast_fn = type(default) if default else lambda x: x
assert callable(typecast_fn), "typecast_fn is not callable!"
value = os.getenv(varname)
return typecast_fn(value) if value else default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment