glue/glue.py

34 lines
1.0 KiB
Python
Raw Normal View History

2014-10-30 18:27:36 +00:00
import collections
2014-10-30 18:07:41 +00:00
2014-10-30 18:37:21 +00:00
2014-10-30 17:49:31 +00:00
def glue(*args, **kwargs):
2014-10-30 18:37:21 +00:00
"""
Glue takes in any number of arguments, named or not, and any depth list
It will flatten them all and return them joined with spaces.
"""
def _flatten(l):
"""
from: Cristian at http://stackoverflow.com/a/2158532
"""
2014-10-30 18:27:36 +00:00
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
2014-10-30 18:37:21 +00:00
for sub in _flatten(el):
2014-10-30 18:27:36 +00:00
yield sub
else:
yield el
2014-10-30 18:37:21 +00:00
# I dont care what order you submit them in, they will be alphabetical
kwargs = collections.OrderedDict(
sorted(kwargs.items(), key=lambda t: t[0]))
2014-10-30 18:50:07 +00:00
what_to_glue = list(args)
2014-10-30 18:37:21 +00:00
# Ignore all your keys, because you're doing this wrong anyway
2014-10-30 18:50:07 +00:00
what_to_glue.extend([v for k, v in kwargs.iteritems()])
2014-10-30 18:37:21 +00:00
# flatten crap out of this!
2014-10-30 18:50:07 +00:00
what_to_glue = _flatten(what_to_glue)
2014-10-30 18:37:21 +00:00
# safeguard against nonstrings
return " ".join([str(x) for x in what_to_glue])