Skip to content

Expr

Excel formula expressions built from Python operators.

Every node is a str subclass whose string value is the finished, =-prefixed formula, so an expression can be assigned straight to an openpyxl cell::

ws["B5"] = cell("B3") - cell("B4")   # cell gets "=B3-B4"

Nesting uses :attr:Expr.text (the body, without the =) rather than the string value. That distinction is the one invariant holding the whole module together.

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)

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

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

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)

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)

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)