Skip to content

Commit

Permalink
Merge pull request #10 from yandex-qatools/fix_flatten_blowingup_if_g…
Browse files Browse the repository at this point in the history
…iven_noniterable

Check that given thing is actually iterable before trying to iterate over it
  • Loading branch information
pupssman committed Mar 3, 2015
2 parents 4621feb + 2f66e5c commit 511c0e0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
14 changes: 7 additions & 7 deletions builders/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ def flatten(l):
Generator that flattens iterable infinitely. If an item is iterable, ``flatten`` descends on it.
If it is callable, it descends on the call result (with no arguments), and it yields the item itself otherwise.
"""
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
if isinstance(l, collections.Iterable) and not isinstance(l, basestring):
for el in l:
for sub in flatten(el):
yield sub
elif callable(el):
for sub in flatten(el()):
yield sub
else:
yield el
elif callable(l):
for sub in flatten(l()):
yield sub
else:
yield l


class Builder:
Expand Down
12 changes: 12 additions & 0 deletions builders/tests/test_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,18 @@ def test_flatten():
assert list(flatten(l)) == [1, 2, 3, 4, 5, 'ololo']


def test_flatten_noniterable():
y = 100
assert list(flatten(y)) == [y]


def test_flatten_function_returning_noniterable():
def y():
return 100

assert list(flatten(y)) == [100]


def test_flatten_callable():
def x():
return [1, 2, 3]
Expand Down

0 comments on commit 511c0e0

Please sign in to comment.