Katkat

Review a Hand-Rolled Python CSV Serializer for Correctness and Performance Bugs

MercorSoftware Engineer · Technical Screen

Last updated

A code review question on a short Python function that turns a table of rows into CSV text. Candidates must find its correctness and performance problems and write a fixed version, which tests delimiter handling, string building in Python, non-string cells, CSV quoting and escaping rules, and how to verify the fix.

You are reviewing this Python function, which is meant to turn a table (a list of rows, each row 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

Spot the issues with this code. For each issue, give an input that triggers it and explain what goes wrong. Then show how you would fix the function.

Clarifying Questions

  • Which CSV conventions must the output follow: comma delimiter, double-quote quoting, CRLF or LF line endings? Who consumes the file: a spreadsheet application, another service, a standard parser?
  • What cell types can appear: only strings, or also numbers, None, dates and booleans?
  • Can rows have different lengths, and is there a header row?
  • How large can a table be? Must the output be written to a file or an HTTP response as it is produced?

Hints

Hint 1

Read it back: Feed the output to a standard CSV reader in your head and check whether you get the original table back, cell for cell. Then try cells that contain the characters CSV itself uses.

Hint 2

Beyond correctness: Some issues only show up with large tables, or with cells that are not strings.

Follow-up questions

  • How would you stream a very large table to a file or an HTTP response without building the whole string in memory?
  • A user opens the exported file in a spreadsheet application, and a cell that starts with `=` is evaluated as a formula. What is the risk, and how would you mitigate it?
  • How would you test the function so that quoting bugs are caught automatically?