{"record":{"id":"59fd3b59a8425c5b","repo":"pathwaycom/pathway","slug":"you-cannot-iterate-over-mock-class","errorCode":null,"errorMessage":"You cannot iterate over mock class.","messagePattern":"You cannot iterate over mock class\\.","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"python/pathway/internals/thisclass.py","lineNumber":107,"sourceCode":"    ) -> expr.ColumnReference | ThisMetaclass:\n        if isinstance(arg, expr.ColumnReference):\n            if isinstance(arg.table, ThisMetaclass):\n                assert arg.table is self\n            return arg.table._get_colref_by_name(arg.name, KeyError)\n        elif isinstance(arg, str):\n            if arg.startswith(KEY_GUARD):\n                return self\n            else:\n                return self._get_colref_by_name(arg, KeyError)\n        else:\n            return self._create_mock(\"__getitem__\", [arg], {})\n\n    @trace_user_frame\n    def __iter__(self):\n        class subclass(self, iter_guard):  # type: ignore[valid-type,misc]\n            @classmethod\n            def __iter__(self):\n                raise TypeError(\"You cannot iterate over mock class.\")\n\n        subclass.__qualname__ = self.__qualname__ + \".\" + \"__iter__\" + \"(...)\"\n        subclass.__name__ = \"__iter__\"\n        return iter([subclass])\n\n    def keys(self):\n        # _key_guard_counter is necessary, otherwise key-collisions happen\n        return [f\"{KEY_GUARD}_{next(_key_guard_counter)}\"]\n\n    @trace_user_frame\n    def __call__(self):\n        raise TypeError(\"You cannot instantiate `this` class.\")\n\n    def pointer_from(\n        self, *args: Any, optional=False, instance: expr.ColumnReference | None = None\n    ):\n        return expr.PointerExpression(self, *args, optional=optional, instance=instance)  # type: ignore[arg-type]\n","sourceCodeStart":89,"sourceCodeEnd":125,"githubUrl":"https://github.com/pathwaycom/pathway/blob/fa2f74a4649b7c5908690cf60137263d8d80de5f/python/pathway/internals/thisclass.py#L89-L125","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["To enumerate columns, use the table's schema instead: [f.name for f in table.typehints()] or table.schema.keys() depending on API version","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","Remove loops of the form 'for c in pw.this' and drive them from the schema or a plain list of names"],"exampleFix":"# before\nfor col in pw.this:\n    print(col)  # TypeError: cannot iterate over mock class\n\n# after\nfor name in table.schema.column_names():\n    print(name)","handlingStrategy":"validation","validationCode":"# Never iterate pw.this; get columns from the schema instead\nschema = table.schema  # or [f.name for f in table.typehints()]\nfor name in schema.column_names():\n    ref = pw.this[name]","typeGuard":null,"tryCatchPattern":"try:\n    cols = list(pw.this)\nexcept TypeError:\n    cols = list(table.schema.column_names())","preventionTips":["Treat pw.this as a reference builder only, never as a container","Enumerate columns via table.schema","Avoid **pw.this unpacking in select calls"],"tags":["pathway","this","iteration","typeerror"],"backgroundTag":null,"analyzedSha":"fa2f74a4649b7c5908690cf60137263d8d80de5f","analyzedAt":"2026-08-15T01:48:17.006Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}