add custom separator

This commit is contained in:
Tyrel Souza 2017-01-23 10:27:56 -05:00
parent 6c3238730a
commit 55d8eb8254
No known key found for this signature in database
GPG Key ID: 2EECB5087209E6A5
2 changed files with 14 additions and 2 deletions

12
glue.py
View File

@ -4,7 +4,9 @@ import collections
def glue(*args, **kwargs): def glue(*args, **kwargs):
""" """
Glue takes in any number of arguments, named or not, and any depth list 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. 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): def _flatten(l):
@ -19,6 +21,10 @@ def glue(*args, **kwargs):
else: else:
yield el 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 # I dont care what order you submit them in, they will be alphabetical
kwargs = collections.OrderedDict( kwargs = collections.OrderedDict(
sorted(kwargs.items(), key=lambda t: t[0])) sorted(kwargs.items(), key=lambda t: t[0]))
@ -30,5 +36,7 @@ def glue(*args, **kwargs):
# flatten crap out of this! # flatten crap out of this!
what_to_glue = _flatten(what_to_glue) what_to_glue = _flatten(what_to_glue)
#set separator
# safeguard against nonstrings # safeguard against nonstrings
return " ".join([str(x) for x in what_to_glue]) return separator.join(str(x) for x in what_to_glue)

View File

@ -8,6 +8,10 @@ class GlueTests(unittest.TestCase):
output = glue("why", "would", "you", "run", "these", "tests") output = glue("why", "would", "you", "run", "these", "tests")
assert output == "why would you run these tests" assert output == "why would you run these tests"
def test_tuple_custom_separator(self):
output = glue("why", "would", "you", separator=",")
assert output == "why,would,you"
def test_tuple_and_named(self): def test_tuple_and_named(self):
output = glue("why", "would", "you", "run", "these", "tests", who="bozo") output = glue("why", "would", "you", "run", "these", "tests", who="bozo")
assert output == "why would you run these tests bozo" assert output == "why would you run these tests bozo"