pathwaycom/pathway · error · TypeError

You cannot iterate over mock class.

Error message

You cannot iterate over mock class.

What it means

Raised when user code iterates over pw.this (or a ThisMetaclass mock). this is a special proxy for building column references and defines no real columns to iterate, so __iter__ is instrumented to raise TypeError with a location-tagged subclass instead of failing silently or producing garbage.

Source

Thrown at python/pathway/internals/thisclass.py:107

    ) -> expr.ColumnReference | ThisMetaclass:
        if isinstance(arg, expr.ColumnReference):
            if isinstance(arg.table, ThisMetaclass):
                assert arg.table is self
            return arg.table._get_colref_by_name(arg.name, KeyError)
        elif isinstance(arg, str):
            if arg.startswith(KEY_GUARD):
                return self
            else:
                return self._get_colref_by_name(arg, KeyError)
        else:
            return self._create_mock("__getitem__", [arg], {})

    @trace_user_frame
    def __iter__(self):
        class subclass(self, iter_guard):  # type: ignore[valid-type,misc]
            @classmethod
            def __iter__(self):
                raise TypeError("You cannot iterate over mock class.")

        subclass.__qualname__ = self.__qualname__ + "." + "__iter__" + "(...)"
        subclass.__name__ = "__iter__"
        return iter([subclass])

    def keys(self):
        # _key_guard_counter is necessary, otherwise key-collisions happen
        return [f"{KEY_GUARD}_{next(_key_guard_counter)}"]

    @trace_user_frame
    def __call__(self):
        raise TypeError("You cannot instantiate `this` class.")

    def pointer_from(
        self, *args: Any, optional=False, instance: expr.ColumnReference | None = None
    ):
        return expr.PointerExpression(self, *args, optional=optional, instance=instance)  # type: ignore[arg-type]

View on GitHub (pinned to fa2f74a464)

Solutions

  1. To enumerate columns, use the table's schema instead: [f.name for f in table.typehints()] or table.schema.keys() depending on API version
  2. To select all columns, just call table.select() with no args or use table itself; to copy columns use table.with_columns(), not **pw.this
  3. Remove loops of the form 'for c in pw.this' and drive them from the schema or a plain list of names

Example fix

# before
for col in pw.this:
    print(col)  # TypeError: cannot iterate over mock class

# after
for name in table.schema.column_names():
    print(name)
Defensive patterns

Strategy: validation

Validate before calling

# Never iterate pw.this; get columns from the schema instead
schema = table.schema  # or [f.name for f in table.typehints()]
for name in schema.column_names():
    ref = pw.this[name]

Try / catch

try:
    cols = list(pw.this)
except TypeError:
    cols = list(table.schema.column_names())

Prevention

When it happens

Trigger: for col in pw.this: ...; dict(pw.this); **pw.this unpacking; passing pw.this where an iterable of column names is expected (e.g. select(*pw.this) misuse or list comprehension over this); using this as **kwargs source: table.select(**pw.this).

Common situations: Trying to dynamically enumerate columns of a table (the right tool is table.schema or table.columns); writing generic code that unpacks objects with keys()/** and hitting the mock protocol Pathway installs for this.

Related errors


AI-assisted analysis of pathwaycom/pathway@fa2f74a464 (2026-08-15). Data as JSON: /api/errors/59fd3b59a8425c5b. Report an issue: GitHub.