def _listlike_guard(obj, name, iterable_only=False):
"""
We frequently require passed objects to support iteration or
containment expressions, but not be strings. (Of course, strings
support iteration and containment, but not usefully.) If the passed
object is a string, we'll wrap it in a tuple and return it. If it's
already an iterable, we'll return it as-is. Otherwise, we'll raise a
TypeError.
"""
required_type = (_Iterable,) if iterable_only else (_Container, _Iterable)
required_type_name = ' or '.join(t.__name__ for t in required_type)
if not isinstance(obj, required_type):
raise ValueError('{} must be of type {}'.format(name, required_type_name))
# at this point it is definitely the right type, but might be a string
if isinstance(obj, basestring):
logging.warning('{} passed as a string; should be list-like'.format(name))
return (obj,)
return obj
评论列表
文章目录