Skip to content

Index

Build Excel formulas with Python operators.

Cell references are objects, so Python's own operators assemble the formula and a precedence-aware renderer parenthesises it correctly::

from pycountant.excel import cell, rng, Ref, F

rev, cost = cell("B3"), cell("B4")
ws["B5"] = rev - cost  # =B3-B4
ws["B6"] = (rev - cost) / rev  # =(B3-B4)/B3
ws["B7"] = rng("B3:B10").sum() * 1.2  # =SUM(B3:B10)*1.2

Or let Sheet hand you the reference as you write, so no coordinate is typed twice::

s = Sheet(ws)
rev, cost = s.put("B2", 1000), s.put("B3", 600)
s.put("B4", (rev - cost) / rev)  # =(B2-B3)/B2

Expressions are str subclasses whose value is the finished formula, so they can be assigned straight to an openpyxl cell. Nothing here imports openpyxl.

BinOp

Bases: Expr

A binary operation between two expressions.

Source code in src/pycountant/excel/expr.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
class BinOp(Expr):
    """A binary operation between two expressions."""

    op: str
    left: Expr
    right: Expr

    def __new__(cls, op: str, left, right, prec: int) -> BinOp:
        left, right = lit(left), lit(right)
        text = left._operand(prec) + op + right._operand(prec, right=True, op=op)
        obj = cls._make(text, prec)
        obj.op, obj.left, obj.right = op, left, right
        return obj

    def shift(self, rows: int = 0, cols: int = 0) -> BinOp:
        return BinOp(self.op, self.left.shift(rows, cols), self.right.shift(rows, cols), self._prec)

CellRef

Bases: Expr

A single cell, e.g. B3, $B$3 or 'Source Data'!B3.

Source code in src/pycountant/excel/refs.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
class CellRef(Expr):
    """A single cell, e.g. ``B3``, ``$B$3`` or ``'Source Data'!B3``."""

    row: int
    col: int
    abs_row: bool
    abs_col: bool
    sheet: str | None
    home: str | None

    def __new__(
        cls, row: int, col: int, *, abs_row: bool = False, abs_col: bool = False, sheet=None, home=None
    ) -> CellRef:
        if not 1 <= row <= MAX_ROW:
            raise ValueError(f"row {row} out of range 1..{MAX_ROW}")
        name = sheet_name(sheet)
        text = sheet_prefix(name) + ("$" if abs_col else "") + col_letter(col) + ("$" if abs_row else "") + str(row)
        obj = cls._make(text, P_ATOM)
        obj.row, obj.col = row, col
        obj.abs_row, obj.abs_col, obj.sheet = abs_row, abs_col, name
        # The sheet this ref was written to.  Never rendered -- it only makes
        # .qualified() possible without retyping the sheet name.
        obj.home = sheet_name(home) or name
        return obj

    @property
    def coordinate(self) -> str:
        """The bare ``B3`` coordinate, without sheet or ``$`` markers."""
        return f"{col_letter(self.col)}{self.row}"

    def rel_text(self) -> str:
        """This cell's text without the sheet prefix, keeping any ``$`` markers."""
        return ("$" if self.abs_col else "") + col_letter(self.col) + ("$" if self.abs_row else "") + str(self.row)

    def _replace(
        self,
        *,
        row: int | _Keep = _KEEP,
        col: int | _Keep = _KEEP,
        abs_row: bool | _Keep = _KEEP,
        abs_col: bool | _Keep = _KEEP,
        sheet: str | None | _Keep = _KEEP,
        home: str | None | _Keep = _KEEP,
    ) -> CellRef:
        """A copy of this reference with the named fields changed."""
        return CellRef(
            self.row if isinstance(row, _Keep) else row,
            self.col if isinstance(col, _Keep) else col,
            abs_row=self.abs_row if isinstance(abs_row, _Keep) else abs_row,
            abs_col=self.abs_col if isinstance(abs_col, _Keep) else abs_col,
            sheet=self.sheet if isinstance(sheet, _Keep) else sheet,
            home=self.home if isinstance(home, _Keep) else home,
        )

    def offset(self, rows: int = 0, cols: int = 0) -> CellRef:
        """A new reference moved by ``rows`` down and ``cols`` right."""
        return self._replace(row=self.row + rows, col=self.col + cols)

    def shift(self, rows: int = 0, cols: int = 0) -> CellRef:
        return self._replace(
            row=self.row if self.abs_row else self.row + rows,
            col=self.col if self.abs_col else self.col + cols,
        )

    def abs(self) -> CellRef:
        """Lock both row and column: ``$B$3``."""
        return self._replace(abs_row=True, abs_col=True)

    def abs_r(self) -> CellRef:
        """Lock the row only: ``B$3``."""
        return self._replace(abs_row=True)

    def abs_c(self) -> CellRef:
        """Lock the column only: ``$B3``."""
        return self._replace(abs_col=True)

    def rel(self) -> CellRef:
        """Drop all ``$`` locking."""
        return self._replace(abs_row=False, abs_col=False)

    def on(self, sheet) -> CellRef:
        """The same cell, qualified with another sheet."""
        return self._replace(sheet=sheet)

    def qualified(self) -> CellRef:
        """Qualify with the sheet this ref came from, for use in another sheet."""
        if self.sheet is not None:
            return self
        if self.home is None:
            raise ValueError(f"{self!r} has no home sheet to qualify with; use .on(sheet) to name one explicitly")
        return self._replace(sheet=self.home)

    def bare(self) -> CellRef:
        """Drop the sheet prefix, keeping the home sheet for later qualification."""
        return self._replace(sheet=None)

    def to(self, other: CellRef) -> RangeRef:
        """The rectangular range spanning this cell and ``other``."""
        return RangeRef(self, other)

coordinate property

The bare B3 coordinate, without sheet or $ markers.

abs()

Lock both row and column: $B$3.

Source code in src/pycountant/excel/refs.py
152
153
154
def abs(self) -> CellRef:
    """Lock both row and column: ``$B$3``."""
    return self._replace(abs_row=True, abs_col=True)

abs_c()

Lock the column only: $B3.

Source code in src/pycountant/excel/refs.py
160
161
162
def abs_c(self) -> CellRef:
    """Lock the column only: ``$B3``."""
    return self._replace(abs_col=True)

abs_r()

Lock the row only: B$3.

Source code in src/pycountant/excel/refs.py
156
157
158
def abs_r(self) -> CellRef:
    """Lock the row only: ``B$3``."""
    return self._replace(abs_row=True)

bare()

Drop the sheet prefix, keeping the home sheet for later qualification.

Source code in src/pycountant/excel/refs.py
180
181
182
def bare(self) -> CellRef:
    """Drop the sheet prefix, keeping the home sheet for later qualification."""
    return self._replace(sheet=None)

offset(rows=0, cols=0)

A new reference moved by rows down and cols right.

Source code in src/pycountant/excel/refs.py
142
143
144
def offset(self, rows: int = 0, cols: int = 0) -> CellRef:
    """A new reference moved by ``rows`` down and ``cols`` right."""
    return self._replace(row=self.row + rows, col=self.col + cols)

on(sheet)

The same cell, qualified with another sheet.

Source code in src/pycountant/excel/refs.py
168
169
170
def on(self, sheet) -> CellRef:
    """The same cell, qualified with another sheet."""
    return self._replace(sheet=sheet)

qualified()

Qualify with the sheet this ref came from, for use in another sheet.

Source code in src/pycountant/excel/refs.py
172
173
174
175
176
177
178
def qualified(self) -> CellRef:
    """Qualify with the sheet this ref came from, for use in another sheet."""
    if self.sheet is not None:
        return self
    if self.home is None:
        raise ValueError(f"{self!r} has no home sheet to qualify with; use .on(sheet) to name one explicitly")
    return self._replace(sheet=self.home)

rel()

Drop all $ locking.

Source code in src/pycountant/excel/refs.py
164
165
166
def rel(self) -> CellRef:
    """Drop all ``$`` locking."""
    return self._replace(abs_row=False, abs_col=False)

rel_text()

This cell's text without the sheet prefix, keeping any $ markers.

Source code in src/pycountant/excel/refs.py
118
119
120
def rel_text(self) -> str:
    """This cell's text without the sheet prefix, keeping any ``$`` markers."""
    return ("$" if self.abs_col else "") + col_letter(self.col) + ("$" if self.abs_row else "") + str(self.row)

to(other)

The rectangular range spanning this cell and other.

Source code in src/pycountant/excel/refs.py
184
185
186
def to(self, other: CellRef) -> RangeRef:
    """The rectangular range spanning this cell and ``other``."""
    return RangeRef(self, other)

Expr

Bases: str

Base class for every formula fragment.

The str value is the complete formula ("=B3-B4"); :attr:text is the body ("B3-B4"). Composition always reads :attr:text.

Source code in src/pycountant/excel/expr.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
class Expr(str):
    """Base class for every formula fragment.

    The ``str`` value is the complete formula (``"=B3-B4"``); :attr:`text` is the
    body (``"B3-B4"``).  Composition always reads :attr:`text`.
    """

    _text: str
    _prec: int

    def __new__(cls, text: str, prec: int = P_ATOM) -> Self:
        return cls._make(text, prec)

    @classmethod
    def _make(cls, text: str, prec: int) -> Self:
        # Returning Self, not Expr, is what lets each subclass assign its own
        # attributes to the result and return it as its own type.
        obj = str.__new__(cls, "=" + text)
        obj._text = text
        obj._prec = prec
        return obj

    @property
    def text(self) -> str:
        """The formula body, without the leading ``=``."""
        return self._text

    @property
    def formula(self) -> str:
        """The complete formula as a plain ``str``, including the leading ``=``."""
        return "=" + self._text

    def __repr__(self) -> str:
        return f"{type(self).__name__}({self._text!r})"

    # -- composition ------------------------------------------------------------
    def _operand(self, parent_prec: int, *, right: bool = False, op: str = "") -> str:
        """This expression's text, parenthesised only if the parent would misread it."""
        if self._prec < parent_prec:
            return f"({self._text})"
        if right and self._prec == parent_prec and op in _RIGHT_NEEDS_PARENS:
            return f"({self._text})"
        return self._text

    def shift(self, rows: int = 0, cols: int = 0) -> Expr:
        """Return a copy with every *relative* reference moved by ``rows``/``cols``.

        Absolute (``$``-locked) components are left alone.  Nodes without references
        return themselves.
        """
        return self

    # -- arithmetic -------------------------------------------------------------
    def __add__(self, other):
        return BinOp("+", self, other, P_ADD)

    def __radd__(self, other):
        return BinOp("+", other, self, P_ADD)

    def __sub__(self, other):
        return BinOp("-", self, other, P_ADD)

    def __rsub__(self, other):
        return BinOp("-", other, self, P_ADD)

    def __mul__(self, other):
        return BinOp("*", self, other, P_MUL)

    def __rmul__(self, other):
        return BinOp("*", other, self, P_MUL)

    def __truediv__(self, other):
        return BinOp("/", self, other, P_MUL)

    def __rtruediv__(self, other):
        return BinOp("/", other, self, P_MUL)

    def __pow__(self, other):
        return BinOp("^", self, other, P_POW)

    def __rpow__(self, other):
        return BinOp("^", other, self, P_POW)

    # Excel's "&" is string concatenation, not boolean AND.  Use F.AND(...) for that.
    def __and__(self, other):
        return BinOp("&", self, other, P_CONCAT)

    def __rand__(self, other):
        return BinOp("&", other, self, P_CONCAT)

    def __neg__(self):
        return UnaryOp("-", self)

    def __pos__(self):
        return self

    def __mod__(self, other):
        raise TypeError(
            "'%' is not an Excel binary operator (and would otherwise be Python "
            "string formatting here). Use F.MOD(a, b), or .pct() for a postfix %."
        )

    __rmod__ = __mod__

    def pct(self) -> Expr:
        """Postfix percent: ``x.pct()`` renders ``x%``."""
        return UnaryOp("%", self, postfix=True)

    # -- comparisons ------------------------------------------------------------
    # Deliberately methods rather than operator overloads, so "==" and hash() keep
    # their native str behaviour and expressions stay usable as dict keys.
    def eq(self, other):
        return BinOp("=", self, other, P_CMP)

    def ne(self, other):
        return BinOp("<>", self, other, P_CMP)

    def lt(self, other):
        return BinOp("<", self, other, P_CMP)

    def le(self, other):
        return BinOp("<=", self, other, P_CMP)

    def gt(self, other):
        return BinOp(">", self, other, P_CMP)

    def ge(self, other):
        return BinOp(">=", self, other, P_CMP)

formula property

The complete formula as a plain str, including the leading =.

text property

The formula body, without the leading =.

pct()

Postfix percent: x.pct() renders x%.

Source code in src/pycountant/excel/expr.py
158
159
160
def pct(self) -> Expr:
    """Postfix percent: ``x.pct()`` renders ``x%``."""
    return UnaryOp("%", self, postfix=True)

shift(rows=0, cols=0)

Return a copy with every relative reference moved by rows/cols.

Absolute ($-locked) components are left alone. Nodes without references return themselves.

Source code in src/pycountant/excel/expr.py
 98
 99
100
101
102
103
104
def shift(self, rows: int = 0, cols: int = 0) -> Expr:
    """Return a copy with every *relative* reference moved by ``rows``/``cols``.

    Absolute (``$``-locked) components are left alone.  Nodes without references
    return themselves.
    """
    return self

Func

Bases: Expr

A worksheet function call.

None renders as an omitted argument, so Func("VLOOKUP", a, b, c, None) gives VLOOKUP(a,b,c,).

Source code in src/pycountant/excel/functions.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
class Func(Expr):
    """A worksheet function call.

    ``None`` renders as an omitted argument, so ``Func("VLOOKUP", a, b, c, None)``
    gives ``VLOOKUP(a,b,c,)``.
    """

    name: str
    args: tuple

    def __new__(cls, name: str, *args, check: bool = True) -> Func:
        if check:
            _check_name(name, len(args))
        parts = tuple(lit(a) for a in args)
        text = f"{stored_name(name)}({','.join(p.text for p in parts)})"
        obj = cls._make(text, P_ATOM)
        obj.name, obj.args = name, parts
        return obj

    def shift(self, rows: int = 0, cols: int = 0) -> Func:
        # Already validated when first built -- and shifting cannot change arity.
        return Func(self.name, *(a.shift(rows, cols) for a in self.args), check=False)

Lit

Bases: Expr

A Python value rendered as an Excel literal.

Source code in src/pycountant/excel/expr.py
189
190
191
192
193
194
195
196
197
198
class Lit(Expr):
    """A Python value rendered as an Excel literal."""

    _value: object

    def __new__(cls, value) -> Lit:
        text, prec = _render_literal(value)
        obj = cls._make(text, prec)
        obj._value = value
        return obj

RangeRef

Bases: Expr

A range: B3:B10, a whole column B:B, or a whole row 3:3.

Source code in src/pycountant/excel/refs.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
class RangeRef(Expr):
    """A range: ``B3:B10``, a whole column ``B:B``, or a whole row ``3:3``."""

    start: str
    end: str
    sheet: str | None
    home: str | None

    def __new__(cls, start, end=None, *, sheet=None, home=None) -> RangeRef:
        if end is None:
            raise TypeError("RangeRef needs both a start and an end")
        name = sheet_name(sheet)
        if isinstance(start, CellRef) and isinstance(end, CellRef):
            # A cell's own sheet wins if none was passed explicitly.
            name = name if name is not None else start.sheet
            home = home if home is not None else start.home
            start_txt = start.rel_text()
            end_txt = end.rel_text()
        else:
            start_txt, end_txt = str(start), str(end)
        obj = cls._make(f"{sheet_prefix(name)}{start_txt}:{end_txt}", P_REF)
        obj.start, obj.end, obj.sheet = start_txt, end_txt, name
        obj.home = sheet_name(home) or name
        return obj

    @property
    def coordinate(self) -> str:
        """The bare ``B3:B10``, without the sheet prefix."""
        return f"{self.start}:{self.end}"

    def on(self, sheet) -> RangeRef:
        return RangeRef(self.start, self.end, sheet=sheet, home=self.home)

    def qualified(self) -> RangeRef:
        """Qualify with the sheet this range came from."""
        if self.sheet is not None:
            return self
        if self.home is None:
            raise ValueError(f"{self!r} has no home sheet to qualify with")
        return RangeRef(self.start, self.end, sheet=self.home)

    def bare(self) -> RangeRef:
        """Drop the sheet prefix, keeping the home sheet."""
        return RangeRef(self.start, self.end, home=self.home)

    def shift(self, rows: int = 0, cols: int = 0) -> RangeRef:
        return RangeRef(
            _shift_part(self.start, rows, cols), _shift_part(self.end, rows, cols), sheet=self.sheet, home=self.home
        )

    # Convenience aggregates.  Imported lazily to keep functions.py free to import
    # this module for its own type checks.
    def sum(self):
        return self._fn("SUM")

    def average(self):
        return self._fn("AVERAGE")

    # NOTE: this shadows str.count, so RangeRef is the one Expr subclass where
    # "expr.count(substring)" raises instead of counting characters.  Kept because
    # .count() is documented API and renaming it would break callers; the
    # alternative, dispatching on the argument, would be worse.  Reach for
    # F.COUNT(rng) if the shadowing ever bites.
    def count(self):  # pyright: ignore[reportIncompatibleMethodOverride]
        return self._fn("COUNT")

    def counta(self):
        return self._fn("COUNTA")

    def min(self):
        return self._fn("MIN")

    def max(self):
        return self._fn("MAX")

    def _fn(self, name: str):
        from .functions import Func

        return Func(name, self)

coordinate property

The bare B3:B10, without the sheet prefix.

bare()

Drop the sheet prefix, keeping the home sheet.

Source code in src/pycountant/excel/refs.py
230
231
232
def bare(self) -> RangeRef:
    """Drop the sheet prefix, keeping the home sheet."""
    return RangeRef(self.start, self.end, home=self.home)

qualified()

Qualify with the sheet this range came from.

Source code in src/pycountant/excel/refs.py
222
223
224
225
226
227
228
def qualified(self) -> RangeRef:
    """Qualify with the sheet this range came from."""
    if self.sheet is not None:
        return self
    if self.home is None:
        raise ValueError(f"{self!r} has no home sheet to qualify with")
    return RangeRef(self.start, self.end, sheet=self.home)

Raw

Bases: Expr

Verbatim formula text.

Parenthesised whenever it is nested, because its internal structure is unknown and Raw("A1+B1") * 2 must not silently become A1+B1*2. Pass atomic=True when the text is a single self-contained term.

Source code in src/pycountant/excel/expr.py
230
231
232
233
234
235
236
237
238
239
class Raw(Expr):
    """Verbatim formula text.

    Parenthesised whenever it is nested, because its internal structure is unknown
    and ``Raw("A1+B1") * 2`` must not silently become ``A1+B1*2``.  Pass
    ``atomic=True`` when the text is a single self-contained term.
    """

    def __new__(cls, text: str, *, atomic: bool = False) -> Raw:
        return cls._make(text, P_ATOM if atomic else P_CMP)

Ref

A sheet-bound factory for references.

Takes an openpyxl worksheet (duck-typed on .title, so openpyxl is never imported) or a plain sheet name::

data = Ref(ws)
data["B3"]        # 'Data'!B3
data["A:A"]       # 'Data'!A:A
data.cell(3, 2)   # 'Data'!B3
Source code in src/pycountant/excel/refs.py
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
class Ref:
    """A sheet-bound factory for references.

    Takes an openpyxl worksheet (duck-typed on ``.title``, so openpyxl is never
    imported) or a plain sheet name::

        data = Ref(ws)
        data["B3"]        # 'Data'!B3
        data["A:A"]       # 'Data'!A:A
        data.cell(3, 2)   # 'Data'!B3
    """

    __slots__ = ("sheet",)

    def __init__(self, sheet):
        self.sheet = sheet_name(sheet)

    def __repr__(self) -> str:
        return f"Ref({self.sheet!r})"

    def __getitem__(self, key: str):
        return cell(key, sheet=self.sheet) if ":" not in key else rng(key, sheet=self.sheet)

    def cell(self, row: int, col: int, **kw) -> CellRef:
        return cell(row, col, sheet=self.sheet, **kw)

    def rng(self, *args, **kw) -> RangeRef:
        return rng(*args, sheet=self.sheet, **kw)

Sheet

A write-and-remember wrapper around an openpyxl worksheet.

openpyxl is never imported: the worksheet is duck-typed on .title and .cell(row=, column=, value=).

Source code in src/pycountant/excel/sheet.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class Sheet:
    """A write-and-remember wrapper around an openpyxl worksheet.

    openpyxl is never imported: the worksheet is duck-typed on ``.title`` and
    ``.cell(row=, column=, value=)``.
    """

    __slots__ = ("ws", "title")

    def __init__(self, ws):
        self.ws = ws
        self.title = sheet_name(ws)

    def __repr__(self) -> str:
        return f"Sheet({self.title!r})"

    def put(self, *args, number_format: str | None = None, **style) -> CellRef:
        """Write a value and return a reference to the cell it landed in.

        Called either as ``put("B2", value)`` or as ``put(row, col, value)``.
        ``value`` may be an expression, in which case the formula is written.

        ``number_format`` and any further keywords are applied to the openpyxl
        cell as attributes, so ``font=``, ``fill=``, ``alignment=`` and ``border=``
        all pass straight through.
        """
        row, col, value = self._parse_target(args)
        target = self.ws.cell(row=row, column=col, value=value)
        if number_format is not None:
            target.number_format = number_format
        for attr, setting in style.items():
            setattr(target, attr, setting)
        return CellRef(row, col, home=self.title)

    @staticmethod
    def _parse_target(args):
        if len(args) == 2 and isinstance(args[0], str):
            coord, value = args
            ref = cell(coord)
            return ref.row, ref.col, value
        if len(args) == 3 and all(isinstance(a, int) for a in args[:2]):
            return args[0], args[1], args[2]
        raise TypeError('put() takes ("B2", value) or (row, col, value)')

    def ref(self, key: str):
        """A reference into this sheet without writing anything."""
        return rng(key, home=self.title) if ":" in key else cell(key, home=self.title)

    __getitem__ = ref

    def cell(self, row: int, col: int, **kw) -> CellRef:
        """A reference by position, without writing anything."""
        return cell(row, col, home=self.title, **kw)

    def span(self, start: CellRef, end: CellRef) -> RangeRef:
        """The range between two references written on this sheet."""
        return rng(start, end, home=self.title)

    def column(self, ref_or_letter) -> RangeRef:
        """The whole column a reference sits in: ``s.column(rev)`` -> ``B:B``."""
        letter = col_letter(ref_or_letter.col) if isinstance(ref_or_letter, CellRef) else ref_or_letter
        return rng(f"{letter}:{letter}", home=self.title)

cell(row, col, **kw)

A reference by position, without writing anything.

Source code in src/pycountant/excel/sheet.py
72
73
74
def cell(self, row: int, col: int, **kw) -> CellRef:
    """A reference by position, without writing anything."""
    return cell(row, col, home=self.title, **kw)

column(ref_or_letter)

The whole column a reference sits in: s.column(rev) -> B:B.

Source code in src/pycountant/excel/sheet.py
80
81
82
83
def column(self, ref_or_letter) -> RangeRef:
    """The whole column a reference sits in: ``s.column(rev)`` -> ``B:B``."""
    letter = col_letter(ref_or_letter.col) if isinstance(ref_or_letter, CellRef) else ref_or_letter
    return rng(f"{letter}:{letter}", home=self.title)

put(*args, number_format=None, **style)

Write a value and return a reference to the cell it landed in.

Called either as put("B2", value) or as put(row, col, value). value may be an expression, in which case the formula is written.

number_format and any further keywords are applied to the openpyxl cell as attributes, so font=, fill=, alignment= and border= all pass straight through.

Source code in src/pycountant/excel/sheet.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def put(self, *args, number_format: str | None = None, **style) -> CellRef:
    """Write a value and return a reference to the cell it landed in.

    Called either as ``put("B2", value)`` or as ``put(row, col, value)``.
    ``value`` may be an expression, in which case the formula is written.

    ``number_format`` and any further keywords are applied to the openpyxl
    cell as attributes, so ``font=``, ``fill=``, ``alignment=`` and ``border=``
    all pass straight through.
    """
    row, col, value = self._parse_target(args)
    target = self.ws.cell(row=row, column=col, value=value)
    if number_format is not None:
        target.number_format = number_format
    for attr, setting in style.items():
        setattr(target, attr, setting)
    return CellRef(row, col, home=self.title)

ref(key)

A reference into this sheet without writing anything.

Source code in src/pycountant/excel/sheet.py
66
67
68
def ref(self, key: str):
    """A reference into this sheet without writing anything."""
    return rng(key, home=self.title) if ":" in key else cell(key, home=self.title)

span(start, end)

The range between two references written on this sheet.

Source code in src/pycountant/excel/sheet.py
76
77
78
def span(self, start: CellRef, end: CellRef) -> RangeRef:
    """The range between two references written on this sheet."""
    return rng(start, end, home=self.title)

UnaryOp

Bases: Expr

A prefix (-) or postfix (%) operation.

Source code in src/pycountant/excel/expr.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
class UnaryOp(Expr):
    """A prefix (``-``) or postfix (``%``) operation."""

    op: str
    operand: Expr
    postfix: bool

    def __new__(cls, op: str, operand, *, postfix: bool = False) -> UnaryOp:
        operand = lit(operand)
        prec = P_PCT if postfix else P_NEG
        body = operand._operand(prec)
        obj = cls._make(body + op if postfix else op + body, prec)
        obj.op, obj.operand, obj.postfix = op, operand, postfix
        return obj

    def shift(self, rows: int = 0, cols: int = 0) -> UnaryOp:
        return UnaryOp(self.op, self.operand.shift(rows, cols), postfix=self.postfix)

cell(*args, sheet=None, home=None, abs_row=None, abs_col=None)

Build a :class:CellRef from "B3" or from (row, col).

cell("$B$3") picks up the $ markers; the abs_row/abs_col keywords override whatever the string said.

Source code in src/pycountant/excel/refs.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def cell(*args, sheet=None, home=None, abs_row: bool | None = None, abs_col: bool | None = None) -> CellRef:
    """Build a :class:`CellRef` from ``"B3"`` or from ``(row, col)``.

    ``cell("$B$3")`` picks up the ``$`` markers; the ``abs_row``/``abs_col``
    keywords override whatever the string said.
    """
    args = list(args)
    if args and not isinstance(args[0], str | int):
        sheet = args.pop(0)  # a worksheet passed positionally
    if len(args) == 1 and isinstance(args[0], str):
        row, col, parsed_row, parsed_col = _parse_a1(args[0])
    elif len(args) == 2 and all(isinstance(a, int) for a in args):
        row, col = args
        parsed_row = parsed_col = False
    else:
        raise TypeError("cell() takes either an A1 string or (row, col) integers")
    return CellRef(
        row,
        col,
        abs_row=parsed_row if abs_row is None else abs_row,
        abs_col=parsed_col if abs_col is None else abs_col,
        sheet=sheet,
        home=home,
    )

col_index(letters)

Column letters to a 1-based index: A -> 1, AA -> 27.

Source code in src/pycountant/excel/refs.py
52
53
54
55
56
57
58
59
60
61
def col_index(letters: str) -> int:
    """Column letters to a 1-based index: ``A -> 1``, ``AA -> 27``."""
    index = 0
    for ch in letters.upper():
        if not "A" <= ch <= "Z":
            raise ValueError(f"invalid column letters: {letters!r}")
        index = index * 26 + (ord(ch) - 64)
    if not 1 <= index <= MAX_COL:
        raise ValueError(f"column {letters!r} out of range A..XFD")
    return index

col_letter(index)

1-based column index to letters: 1 -> A, 27 -> AA.

Source code in src/pycountant/excel/refs.py
41
42
43
44
45
46
47
48
49
def col_letter(index: int) -> str:
    """1-based column index to letters: ``1 -> A``, ``27 -> AA``."""
    if not 1 <= index <= MAX_COL:
        raise ValueError(f"column index {index} out of range 1..{MAX_COL}")
    letters = ""
    while index:
        index, rem = divmod(index - 1, 26)  # bijective base-26
        letters = chr(65 + rem) + letters
    return letters

lit(value)

Coerce a Python value into an :class:Expr, passing existing ones through.

Source code in src/pycountant/excel/expr.py
184
185
186
def lit(value) -> Expr:
    """Coerce a Python value into an :class:`Expr`, passing existing ones through."""
    return value if isinstance(value, Expr) else Lit(value)

rng(*args, sheet=None, home=None)

Build a :class:RangeRef from "B3:B10" or from two cell references.

Source code in src/pycountant/excel/refs.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def rng(*args, sheet=None, home=None) -> RangeRef:
    """Build a :class:`RangeRef` from ``"B3:B10"`` or from two cell references."""
    args = list(args)
    if args and not isinstance(args[0], str) and not isinstance(args[0], CellRef):
        sheet = args.pop(0)
    if len(args) == 1 and isinstance(args[0], str):
        start, _, end = args[0].strip().partition(":")
        if not end:
            raise ValueError(f"not a range: {args[0]!r}")
        for part in (start, end):
            if not (_A1_RE.match(part) or _COL_RE.match(part) or _ROW_RE.match(part)):
                raise ValueError(f"invalid range endpoint {part!r} in {args[0]!r}")
        return RangeRef(start, end, sheet=sheet, home=home)
    if len(args) == 2 and all(isinstance(a, CellRef) for a in args):
        return RangeRef(args[0], args[1], sheet=sheet, home=home)
    raise TypeError('rng() takes an "A1:B2" string or two CellRefs')