Idea: Static Expressions
Fredrik Lundh | June 2006
A static expression is evaluated at the same time as the nearest surrounding function definition.
staticatom(dead link)
Static expressions are evaluated by the surrounding def statement, in that scope, and in lexical order (after the default argument expressions have been evaluated, but before the function object is created).
Static expressions are used to bind to external objects (rather than names), to explicitly precalculate local expressions or subexpressions, and to provide hints to the code generator.
Examples #
The traditional “default argument” object binding hack:
def foo(value, bar=fie.fum): if value == bar: ...
is better written as
def foo(value): if value == static fie.fum: ...
Local data structures can be precalculated:
def foo(value): table = static { 1: "one", 2: 1+1, 3: fie.fum, }
Constant expressions can also be precalculated:
def foo(value): if value < static (math.pi / 2): ... def calc(degree) radian = degree * static (math.pi / 180)
Static expressions can be used to provide hints to the Python runtime; for example, if the foo attributes are all integers, the following if/elif construct can be replaced with a jump table.
def foo(...): var = expression if var == static foo.bar: ... elif var == static foo.fie: ... elif var == static foo.fum: ...
Notes #
See the current python-dev thread titled Switch statement.
PJE suggested a generator expression/yield-style syntax instead, to make the scope clearer: (static expr)
This is somewhat releated to constexpr in the upcoming C++ revision.