if ti.static(condition) 在python scope中也可以起效果嘛



ti.static 是一个给 Taichi 编译器的 hint,意思是「请在编译的时候计算出表达式里的值」,但是 Python scope 里所有的东西都是运行时确定的,而且 ti.static 的参数会在传递给它之前被计算完成,所以不会起什么效果的。

def static(x, *xs):
    """Evaluates a Taichi-scope expression at compile time.

    `static()` is what enables the so-called metaprogramming in Taichi. It is
    in many ways similar to ``constexpr`` in C++.

    See also https://docs.taichi-lang.org/docs/meta.

        x (Any): an expression to be evaluated
        *xs (Any): for Python-ish swapping assignment

        The most common usage of `static()` is for compile-time evaluation::

            >>> cond = False
            >>> @ti.kernel
            >>> def run():
            >>>     if ti.static(cond):
            >>>         do_a()
            >>>     else:
            >>>         do_b()

        Depending on the value of ``cond``, ``run()`` will be directly compiled
        into either ``do_a()`` or ``do_b()``. Thus there won't be a runtime
        condition check.

        Another common usage is for compile-time loop unrolling::

            >>> @ti.kernel
            >>> def run():
            >>>     for i in ti.static(range(3)):
            >>>         print(i)
            >>> # The above will be unrolled to:
            >>> @ti.kernel
            >>> def run():
            >>>     print(0)
            >>>     print(1)
            >>>     print(2)
    if len(xs):  # for python-ish pointer assign: x, y = ti.static(y, x)
        return [static(x)] + [static(x) for x in xs]

    if isinstance(x,
                  (bool, int, float, range, list, tuple, enumerate, _Ndrange,
                   GroupedNDRange, zip, filter, map)) or x is None:
        return x
    if isinstance(x, AnyArray):
        return x
    if isinstance(x, Field):
        return x
    if isinstance(x, (FunctionType, MethodType)):
        return x
    raise ValueError(
        f'Input to ti.static must be compile-time constants or global pointers, instead of {type(x)}'

上面是 ti.static 的源码,可以看到只是做了几个简单判断,然后原样返回。
真正的处理逻辑是在 Taichi 的编译器中的。