Dewey
Dewey

Reputation: 776

explain unfamiliar python syntax -- returning into a list

I totally understand what the right side of this expression is doing. But what's it returning into? In other words, what's the left side doing?

[records, remainder] = ''.join([remainder, tmp]).rsplit(NEWLINE,1)

I'm not familiar with that syntax.

remainder is defined above this line as empty string:

remainder = ''

but records is not defined anywhere in the function.

From the context, it should be accumulating streaming content, but I'm not understanding how.

Upvotes: 2

Views: 114

Answers (3)

Facundo Casco
Facundo Casco

Reputation: 10585

It first joins the content of remainder with the contents of tmp using an empty string as joiner.

''.join([...])

Then it splits this join from the right, using NEWLINE as splitter and only doing one split, that is, it returns two values, one from the beginning to the first occurrence of NEWLINE and another from there to the end.

.rsplit(NEWLINE, 1)

Finally it assigns the first value to records and the second to remainder using tuple unpacking.

a, b = (c, d)

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142126

Not sure about streaming content, but it's easy enough to try this for yourself:

>>> a = 'abc'
>>> b = '\ndef\nghi'
>>> c = (a + b).rsplit('\n', 1)
#['abc\ndef', 'ghi']

Then it uses unpacking to assign two variables (which should be written as):

fst, snd = c

(The []'s are superfluous)

Upvotes: 0

Borealid
Borealid

Reputation: 98469

records is taking the first element of the rsplit's return value. remainder is taking the second.

% python
Python 2.7 (r27:82500, Sep 16 2010, 18:02:00) 
[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> foo = [3, 9]
>>> [records, remainder] = foo
>>> records
3
>>> remainder
9
>>> foo = [3, 9, 10]
>>> [records, remainder] = foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

You actually don't need the square-brackets around [records, remainder], but they're stylistic.

Upvotes: 3

Related Questions