Python, properly · Chapter 29 of 42

Enums

By the end of this chapter you can replace magic strings with an Enum, look members up by value and by name, give members behaviour, and choose between Enum and StrEnum. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Objects
  • 3 tasks
  • Python
  • In the all labs plan

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.

Why you need this

An order's status is one of exactly five words, but in DabbaDrop's code it is just a string, and strings take anything. Bhavna asked why the "delivered today" count was low. Here is every spelling of the status in orders.csv:

import csv

with open("/workspace/data/orders.csv", encoding="utf-8") as f:
    spellings = {row["status"] for row in csv.DictReader(f)}
print(sorted(spellings))
['CANCELLED', 'COOKING', 'DELIVERED', 'cancelled', 'cooking', 'delivered', 'out_for_delivery', 'placed']

Code that tests status == "delivered" misses every DELIVERED. Worse, a typo like status == "deliverd" is valid Python: it is simply never true, and nothing tells you. Kunal wants the five statuses written in one place, so a wrong one fails loudly. That place is an enum.

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    status.py: order statuses as a StrEnum

    Write Status, a StrEnum with five members in this order, each value made by auto(): PLACED, COOKING, OUT_FOR_DELIVERY, DELIVERED, CANCELLED. Their values are then "placed", "cooking", "out_for_delivery", "delivered" and "cancelled", exactly as orders.csv spells them.

    Add a read-only property is_final: True for DELIVERED and CANCELLED, False for the other three.

    The check expects Status("delivered") to be Status.DELIVERED, Status.COOKING == "cooking" to be True, f"{Status.COOKING}" to be "cooking", and Status("deliverd") to raise ValueError.

  2. Task 2

    counts.py: count the messy statuses in orders.csv

    Import Status from your status.py (task 1). Write parse_status(text), which returns the Status for text ignoring spaces around it and capital letters, and raises ValueError for anything else: parse_status(" Delivered ") is Status.DELIVERED, parse_status("deliverd") and parse_status("") raise ValueError.

    Then count_statuses(path), which reads the orders CSV at path and returns a dictionary from Status to the number of rows with that status, counting every row (the duplicate D0101 too). For /workspace/data/orders.csv the counts add up to 601, with DELIVERED and delivered on one key. A file with a misspelt status raises ValueError.

  3. Task 3 · interview question

    Interview: coupon.py, coupons that work out discounts

    Write Coupon, a plain Enum (not a StrEnum) with two members: DABBA10 = "DABBA10" (10% off, rounded down to a whole rupee) and FIRST50 = "FIRST50" (Rs 50 off, but never more than the total).

    discount(total) returns the rupees off: Coupon.DABBA10.discount(245) is 24, Coupon.FIRST50.discount(240) is 50 and Coupon.FIRST50.discount(30) is 30.

    Coupon.from_code(text), a class method, returns the Coupon for a code ignoring spaces and case, None for an empty code, and raises ValueError for an unknown code like "FREE100". It must read every coupon in orders.csv. Coupon.DABBA10 == "DABBA10" is False.

What you will learn

  • Enum: a fixed set of named members, each with a value.
  • Lookups: by value with Vehicle("bike"), by name with Vehicle["BIKE"], and the ValueError for anything else.
  • Members are singletons: compare them with is, and give them methods and properties.
  • StrEnum and auto(): members that are also strings.

More in Objects

Build "Enums" yourself

DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Python, properly are free. This one comes with the all labs plan.