glue/glue.py
2017-01-23 10:27:56 -05:00

43 lines
1.3 KiB
Python

import collections
def glue(*args, **kwargs):
"""
Glue takes in any number of arguments, named or not, and any depth list
It will flatten them all and return them joined with kwargs['separator']
(This is the only kwarg that will be used, anything else will be
included)
"""
def _flatten(l):
"""
from: Cristian at http://stackoverflow.com/a/2158532
"""
for el in l:
if isinstance(el, collections.Iterable)\
and not isinstance(el, basestring):
for sub in _flatten(el):
yield sub
else:
yield el
separator = ' ' # default
if 'separator' in kwargs:
separator = kwargs.pop('separator')
# I dont care what order you submit them in, they will be alphabetical
kwargs = collections.OrderedDict(
sorted(kwargs.items(), key=lambda t: t[0]))
what_to_glue = list(args)
# Ignore all your keys, because you're doing this wrong anyway
what_to_glue.extend([v for k, v in kwargs.iteritems()])
# flatten crap out of this!
what_to_glue = _flatten(what_to_glue)
#set separator
# safeguard against nonstrings
return separator.join(str(x) for x in what_to_glue)