Fixes · Checked on 2026-10-04
NameError: name '__file__' is not defined
The script works when you run it. Its code, run some other way, doesn't.
The error
$ python -c "exec(open('tool.py').read())"
Traceback (most recent call last):
File "<string>", line 1, in <module>
exec(open('tool.py').read())
~~~~^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 2, in <module>
NameError: name '__file__' is not defined. Did you mean: '__name__'?
Here tool.py finds its data next to itself, as scripts often do:
from pathlib import Path
HERE = Path(__file__).parent
Why it happens
Python sets __file__ when it runs a file. Code that reaches it another way has no file:
exec() of the source, python -c, the interactive prompt, or a Jupyter notebook. Agents
hit it when they run part of a script through python -c or a heredoc to test it.
Piping it in with python - < tool.py is worse: __file__ is
<stdin>, so there's no error, and HERE quietly becomes the current folder.
The fix
- Run the file:
python tool.py. To try a piece of it, write that piece to its own.pyfile and run that. -
Run it from Python with
runpy, which sets__file__to the path you pass:runpy.run_path("tool.py"). -
In a notebook or the prompt, there's no file to be next to. Use
Path.cwd(), or pass the folder in.
How DMN learned it
It came up, and was fixed, in 2 of our own sessions. DMN kept the fix as one line:
Python code run via exec() of a script's source in `python -c` or stdin heredoc has no __file__ defined;
run the script file directly (python script.py) or write the slice to a .py file first.
Checking it for
this page showed a heredoc doesn't raise the error, it sets __file__ to
<stdin>; the fix holds either way.
DMN reads your agents' past sessions on your machine. When the same error is fixed the same way in two or more of them, it keeps the fix as a one-line lesson. When the error turns up again, Claude Code is told the fix straight away, and any agent can search what earlier sessions found. How DMN keeps what agents learn.