Skip to content

Refs

Cell and range references.

References are relative by default, so Excel's own fix-up behaviour works normally when someone later edits the workbook by hand. Sheet qualification is always explicit -- it is never inferred from context.

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)

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)

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)

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

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')

sheet_name(sheet)

Accept an openpyxl worksheet (duck-typed on .title) or a plain name.

Source code in src/pycountant/excel/refs.py
64
65
66
67
68
def sheet_name(sheet) -> str | None:
    """Accept an openpyxl worksheet (duck-typed on ``.title``) or a plain name."""
    if sheet is None:
        return None
    return sheet if isinstance(sheet, str) else sheet.title