KatInterview

Fix a Buggy Python Table-to-CSV Function

StringsModel answer
MediumModel answerStringscode-reviewcsvpython

Last updated

Audit a short Python function that flattens rows into CSV text, list its correctness and performance flaws with triggering inputs, and rewrite it safely and efficiently.

A teammate has submitted the following Python helper in a pull request. It is supposed to convert a table, represented as a list of rows where each row is a list of cells, into CSV text.

def to_csv(table):
 output = ""
 for row in table:
 for cell in row:
 output += cell
 output += ","
 output += "\n"
 return output

Review it as you would in a real code review.

  1. List every problem you can find. For each one, give a concrete input that triggers it and explain what goes wrong (what the function returns versus what a correct CSV would look like).
  2. Write a corrected version of the function.
  3. Describe how you would test the fix, and what you would ask the author before settling on the final behavior.

Assume the output will be read back by a standard CSV parser, for example a spreadsheet or Python's csv module.

Hints

Hint 1

Read back the output of a single row such as ["a", "b"]. How many fields does a parser see on that line, and what is the last character before the newline?

Hint 2

Try cells that are not strings (an int, None, a float), and cells that contain a comma, a double quote or a newline. What does each do to the function, and what rule does CSV define for them?

Hint 3

Think about what += on a str does in a loop over many cells, and whether the whole result must exist in memory at once. The standard library already has a tested CSV writer you can point at a file-like object.