{"record":{"id":"5941faaba62da0e1","repo":"pandas-dev/pandas","slug":"name-name-is-not-defined","errorCode":null,"errorMessage":"name '{name}' is not defined","messagePattern":"name '(.+?)' is not defined","errorType":"exception","errorClass":"UndefinedVariableError","httpStatus":null,"severity":"error","filePath":"pandas/core/computation/scope.py","lineNumber":245,"sourceCode":"            if is_local:\n                return self.scope[key]\n\n            # not a local variable so check in resolvers if we have them\n            if self.has_resolvers:\n                return self.resolvers[key]\n\n            # if we're here that means that we have no locals and we also have\n            # no resolvers\n            assert not is_local and not self.has_resolvers\n            return self.scope[key]\n        except KeyError:\n            try:\n                # last ditch effort we look in temporaries\n                # these are created when parsing indexing expressions\n                # e.g., df[df > 0]\n                return self.temps[key]\n            except KeyError as err:\n                raise UndefinedVariableError(key, is_local) from err\n\n    def swapkey(self, old_key: str, new_key: str, new_value=None) -> None:\n        \"\"\"\n        Replace a variable name, with a potentially new value.\n\n        Parameters\n        ----------\n        old_key : str\n            Current variable name to replace\n        new_key : str\n            New variable name to replace `old_key` with\n        new_value : object\n            Value to be replaced along with the possible renaming\n        \"\"\"\n        if self.has_resolvers:\n            maps = self.resolvers.maps + self.scope.maps\n        else:\n            maps = self.scope.maps","sourceCodeStart":227,"sourceCodeEnd":263,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/computation/scope.py#L227-L263","documentation":"Raised as UndefinedVariableError by Scope.resolve when a name used in an eval/query expression cannot be found in locals, resolvers, the global scope, or the temporaries map. The message 'name X is not defined' mirrors Python's own NameError and is pandas' way of telling you the identifier is neither a column nor a bound variable.","triggerScenarios":"df.query('foo > 0') where foo is not a column and not a local; df.eval('bar + 1') with bar undefined; referencing a local variable without the @ prefix (df.query('@x > 0') is required for locals); a typo in a column name; referencing a variable defined in a different frame.","commonSituations":"Forgetting the @ prefix to reference local variables in query/eval; misspelling a column name; expecting a variable from an outer scope that wasn't passed into the eval context; version changes that tightened name resolution.","solutions":["Prefix local variable references with @: df.query('@x > 0') instead of df.query('x > 0').","Verify the column name exists: print(df.columns) and fix typos.","Pass external variables explicitly via the local_dict/resolvers, or use plain boolean indexing df[df.A > x] which uses normal Python scoping.","For computed columns, use df.eval with column names only and pass globals via the engine's namespace."],"exampleFix":"// before\nx = 5\ndf.query('A > x')  # name 'x' is not defined\n\n// after\nx = 5\ndf.query('A > @x')","handlingStrategy":"validation","validationCode":"def check_query_names(df, expr, local_names=()):\n    import re\n    tokens = set(re.findall(r'@?(\\b[A-Za-z_]\\w*\\b)', expr))\n    cols = set(df.columns)\n    locals_ok = {t[1:] for t in re.findall(r'@(\\b[A-Za-z_]\\w*\\b)', expr)}\n    missing = (tokens - cols - locals_ok) - set(local_names)\n    if missing:\n        raise NameError(f'names not defined: {sorted(missing)}')","typeGuard":"def names_resolvable(df, expr, local_scope: dict) -> bool:\n    import re\n    used = set(re.findall(r'\\b[A-Za-z_]\\w*\\b', expr))\n    at_names = set(re.findall(r'@([A-Za-z_]\\w*)', expr))\n    return used.issubset(set(df.columns) | set(local_scope)) and at_names.issubset(set(local_scope))","tryCatchPattern":"from pandas.errors import UndefinedVariableError\ntry:\n    df.query('A > @x')\nexcept UndefinedVariableError as err:\n    # x not in locals: bind it or switch to boolean indexing\n    df[df['A'] > x]","preventionTips":["Prefix every local-variable reference in query/eval with @.","Print df.columns and cross-check identifiers before building a query string.","When in doubt, use df[df['A'] > x] which uses normal Python scoping."],"tags":["eval","query","scope","undefined-variable","name-resolution"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}