Skip to content

Commit ee8c14f

Browse files
committed
Fix: concat() was too eager in escaping iterables; preventing them from being flattened
Also prevent redundantly asking an escaping concat() for its iterator
1 parent ef7f539 commit ee8c14f

1 file changed

Lines changed: 18 additions & 10 deletions

File tree

src/bd2k/util/iterables.py

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -73,18 +73,26 @@ class concat( object ):
7373
7474
Some more example.
7575
76-
>>> list( concat() )
76+
>>> list( concat() ) # empty concat
7777
[]
78-
>>> list( concat( 1 ) )
78+
>>> list( concat( 1 ) ) # non-iterable singleton
7979
[1]
80-
>>> list( concat( concat() ) )
80+
>>> list( concat( concat() ) ) # empty, iterable singleton
8181
[]
82-
>>> list( concat( concat( 1 ) ) )
82+
>>> list( concat( concat( 1 ) ) ) # singleton singleton
8383
[1]
8484
>>> list( concat( 1, concat( 2 ), 3 ) )
8585
[1, 2, 3]
86+
>>> list( concat( 1, [2], 3 ) ) # flattened iterable
87+
[1, 2, 3]
88+
>>> list( concat( 1, concat( [2] ), 3 ) ) # protecting an iterable from being flattened
89+
[1, [2], 3]
90+
>>> list( concat( 1, concat( [2], 3 ), 4 ) ) # protection only works with a single argument
91+
[1, 2, 3, 4]
8692
>>> list( concat( 1, 2, concat( 3, 4 ), 5, 6 ) )
8793
[1, 2, 3, 4, 5, 6]
94+
>>> list( concat( 1, 2, concat( [ 3, 4 ] ), 5, 6 ) )
95+
[1, 2, [3, 4], 5, 6]
8896
8997
Note that while strings are technically iterable, concat() does not flatten them.
9098
@@ -100,13 +108,13 @@ def __init__( self, *args ):
100108

101109
def __iter__( self ):
102110
def expand( x ):
103-
try:
104-
i = x.__iter__( )
105-
except AttributeError:
106-
i = x,
111+
if isinstance( x, concat ) and len( x.args ) == 1:
112+
i = x.args
107113
else:
108-
if isinstance( x, concat ):
109-
i = x.args
114+
try:
115+
i = x.__iter__( )
116+
except AttributeError:
117+
i = x,
110118
return i
111119

112120
return flatten( imap( expand, self.args ) )

0 commit comments

Comments
 (0)