Sub topic 3
Formatting a chain so it reads top to bottom
This chapter assumes you can write basic Python functions, create and inspect a DataFrame, filter rows, and run a simple groupby aggregation. You should also know that most pandas methods return a new DataFrame, which the previous chapters covered. The code here uses only methods you already know, and assign and pipe come later. This chapter is about layout: how to write a chain so that each step is easy to find, read, change, and remove.
The goal: one step per line
A chain is only as readable as its layout. Written on one line, a four-step chain is hard to scan:
result = df.query("quantity > 1").sort_values("price", ascending=False).rename(columns={"price": "unit_price"}).reset_index(drop=True)The convention that fixes this is short:
- Wrap the whole expression in parentheses.
- Put each method call on its own line.
- Start each line with the dot.
- Indent every step by the same amount.
Here is the same chain in that layout. It uses this sample data:
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3, 4],
"region": ["east", "west", "east", "west"],
"price": [10.0, 20.0, 15.0, 5.0],
"quantity": [2, 1, 3, 10],
})
result = (
df
.query("quantity > 1")
.sort_values("price", ascending=False)
.rename(columns={"price": "unit_price"})
.reset_index(drop=True)
)
print(result)The printed output is:
order_id region unit_price quantity
0 3 east 15.0 3
1 1 east 10.0 2
2 4 west 5.0 10Read the chain from top to bottom. It starts with df, keeps orders with more than one item, sorts by price, renames a column, and resets the index. Each line is one transformation, and the order of the lines is the order of the operations.
Why the parentheses matter
Python ends a statement at the end of a line, unless something is still open. This code fails:
result = df
.query("quantity > 1")Python sees result = df as a finished statement. The next line starts with an indent and a dot, so you get an IndentationError ("unexpected indent"). Inside parentheses, Python treats the newlines as ordinary whitespace and keeps reading until the closing parenthesis. That is the whole reason for the outer parentheses. They have no effect on the result, only on how Python parses the lines.
The same rule applies inside a function. A return followed by a chain on the next lines needs its own parentheses:
def bulk_orders(data):
return (
data
.query("quantity > 1")
.sort_values("price", ascending=False)
)
print(bulk_orders(df))Without the parentheses, return data would end the statement on the first line.
Parentheses or backslashes
Python has a second way to continue a line, the backslash. The chain above could be written like this:
result = df \
.query("quantity > 1") \
.sort_values("price", ascending=False)This works, but the parenthesized form is better in practice.
| Aspect | Parentheses | Backslash |
|---|---|---|
| Comments between steps | Allowed | Not allowed |
| Invisible trailing whitespace after the marker | Harmless | A space after `\` is a `SyntaxError` |
| Adding or removing a step | Edit one line | Must keep a `\` on every line except the last |
| Style guides and formatters | Preferred | Discouraged |
The backslash row about whitespace is the one that catches people. \ must be the very last character on its line, so a stray space makes the line a syntax error that is hard to see. Use parentheses and avoid backslashes in chains.
Where to put the dot
Put the dot at the start of each line, not at the end of the previous one:
result = (
df
.query("quantity > 1")
.reset_index(drop=True)
)Python accepts a trailing dot (df. followed by a newline and query(...)), but it hides the method names at the far right edge of each line. With leading dots, the left edge of the block lists the operations in order. You can scan that column to see what the chain does.
There are two common choices for the first line:
dfalone on the first line, as in this chapter. Every method line is the same shape, so you can reorder, delete, or comment out any step without touching the others.df.query(...)on the first line, which is what formatters such as Black and Ruff typically produce. It saves a line, but the first step looks different from the rest.
Choose one style per project. If you run an auto-formatter, it may rewrite your first line, so follow its output rather than fighting it.
Comments inside a chain
A parenthesized chain allows comments between steps. Use them to explain why a step exists, not what the method name already says:
result = (
df
# bulk orders only; single-item orders are handled elsewhere
.query("quantity > 1")
.sort_values("price", ascending=False)
# the sort scrambled the index, so renumber from 0
.reset_index(drop=True)
)Comments also make debugging easy, as the next section shows.
Long arguments get their own lines
A step can be too long for one line, usually when it takes a dictionary or several keyword arguments. Open the call's parentheses and put each argument on its own line, with a trailing comma:
summary = (
df
.groupby("region", as_index=False)
.agg(
total_quantity=("quantity", "sum"),
orders=("order_id", "count"),
avg_price=("price", "mean"),
)
.sort_values("total_quantity", ascending=False)
)
print(summary)The outer chain still has one step per line. The argument list is indented one more level under the step it belongs to, so you can see which arguments go with which method. The trailing comma means that adding a fourth aggregation changes only one line.
Strings need the same care. A long query expression is one string, and you can split it with adjacent string literals inside the call's parentheses:
result = (
df
.query(
"quantity > 1 "
"and region == 'east'"
)
)Python joins adjacent string literals into one string. Keep the trailing space at the end of the first piece, or the two parts will run together as 1and.
Using the layout to debug
One line per step makes it cheap to test the chain. You can comment out the last lines to see the intermediate result:
result = (
df
.query("quantity > 1")
.sort_values("price", ascending=False)
# .rename(columns={"price": "unit_price"})
# .reset_index(drop=True)
)Because every step is a whole line, commenting it out never leaves a broken expression behind. The chain stops at whichever step you left active. Later chapters add pipe for inspecting a chain without editing it.
Common formatting errors
- A trailing comma after the closing parenthesis.
result = (df.query("quantity > 1"),)creates a tuple that contains a DataFrame, not a DataFrame. The error shows up later, for example asAttributeError: 'tuple' object has no attribute 'head'. Never put a comma after the final). - Forgetting to assign the result. A chain that is not assigned or returned computes the result and throws it away. Methods return new objects (see the earlier chapter), so
dfis unchanged. - A step that returns
None. Some methods modify in place and returnNone. A step that returnsNonebreaks the chain on the next line withAttributeError: 'NoneType' object has no attribute .... Keep to methods that return a DataFrame. - Mixed indentation. Python does not require a consistent indent inside parentheses, but readers do. Use four spaces for every step.
A short checklist
Use this when you format a chain:
- Wrap the expression in parentheses, in
return (...)as well as in assignments. - Put one method call per line, each starting with a dot.
- Indent all steps by the same amount.
- Put long argument lists inside the call, one argument per line, with a trailing comma.
- Comment the reason for a step, not its name.
- Assign or return the result, and check that no comma follows the closing parenthesis.
Exercise
This code raises an error. What is the error, and how do you fix it without changing which methods run? result = df .query("quantity > 1") .reset_index(drop=True)
Show answer
Python ends the statement after result = df, so the indented line that starts with a dot raises an IndentationError (unexpected indent). Wrap the whole expression in parentheses: result = ( on the first line, then df, .query("quantity > 1") and .reset_index(drop=True) on separate lines, then ) on its own line. Inside parentheses Python keeps reading across line breaks.
Exercise
A teammate writes summary = (df.groupby("region").agg(total=("quantity", "sum")),) and later gets AttributeError: 'tuple' object has no attribute 'sort_values' when they call summary.sort_values("total"). What is wrong?
Show answer
The comma before the final ) turns the parenthesized expression into a one-element tuple, so summary is a tuple that holds a DataFrame. Remove the trailing comma after the closing parenthesis of agg(...). A trailing comma inside the agg(...) argument list is fine, but not one after the outer parenthesis.