Skip to the page

Core data model · core

Text, bytes, encodings and money with Decimal

str is Unicode text and bytes is raw data, so reading a file needs an encoding. Money needs Decimal (or whole paise), because floats are binary and built-in round() rounds half to even.

The notes

What you must know

  • str is text (Unicode); bytes are raw. Reading a text file decodes bytes with an encoding.
  • Before Python 3.15, open() without encoding uses the locale encoding: UTF-8 on Mac and Linux, usually cp1252 on Windows. UTF-8 bytes for Hindi or Tamil then fail with UnicodeDecodeError or turn into garbage. Python 3.15 uses UTF-8 by default (PEP 686).
  • Always pass encoding=. -X warn_default_encoding (3.10 and later) warns about every open() without one. PYTHONUTF8=1 is a stopgap on older versions.
  • Excel "CSV UTF-8" starts with a byte-order mark. Read it with encoding="utf-8-sig". The characters  at the start are that mark decoded as cp1252.
  • errors="ignore" hides bad bytes silently. Decide with the business: reject the file with a clear message, or errors="replace" with a count in the log.
  • Floats are binary, so most decimals are not exact: round(2.675, 2) gives 2.67. Built-in round() rounds half to even, so round(1.125, 2) is 1.12.
  • Use Decimal built from strings, never from floats (Decimal(1.125) carries the float error), and quantize(Decimal("0.01"), rounding=ROUND_HALF_UP). Or keep whole paise as integers.
  • f"{x:.2f}" does not round half up. Store money in NUMERIC columns and send Decimal as a string in JSON.

The red pen

Common traps: mistake → fix

  • Mistake: errors="ignore" makes the import safe

    Fix: it silently loses data.

  • Mistake: Decimal(1.125) is exact

    Fix: it copies the float error; build it from the string "1.125".

  • Mistake: round() always rounds half up

    Fix: it rounds half to even.

  • Mistake: The partner's file is broken

    Fix: first check the server's default encoding.

Easy to hard

Questions interviewers ask, easy to hard

  1. Why does a CSV import work on a Mac and crash on the Windows server?
  2. What does a UTF-8 byte-order mark look like, and how do you read such a file?
  3. Why can the GST in a billing script be one paisa off?
  4. Why is Decimal(0.1) a bad idea, and what do you use instead?
  5. How would you test a rounding helper?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview