Skip to content

Instantly share code, notes, and snippets.

@DavidAntliff
Created March 15, 2017 01:38
Show Gist options
  • Save DavidAntliff/391ff5cadcec179bf65de14743b60c74 to your computer and use it in GitHub Desktop.
Save DavidAntliff/391ff5cadcec179bf65de14743b60c74 to your computer and use it in GitHub Desktop.
Coerce a scalar or sequence into an iterable
def coerce_iterable(scalar_or_sequence):
"""If scalar_or_sequence is not iterable, wrap it so that the return value is."""
try:
_ = tuple(x for x in scalar_or_sequence)
result = scalar_or_sequence
except TypeError:
# The user has probably specified a single entity and forgotten to
# define it as a proper tuple, so be friendly and handle as a scalar instance:
result = (scalar_or_sequence,)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment