New submission from Terry J. Reedy <>:

'python' sets main.__file__ to ''. 'python' leaves 
__file__ unset.  If PYTHONSTARTUP is set to, 'python' executes in main with __file__ set to '', then unsets __file__ 
before the >>> prompt, as if somefile has not been executed.  Any explicit 
setting of __file__ in somefile is undone.
print(__name__, __file__)
__file__ = ''

> F:\dev\3x> set PYTHONSTARTUP=f:/python/a/
> F:\dev\3x> python
__main__ f:/python/a/
>>> __file__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined

With IDLE, when 'python -m idlelib.idle' is run with '-s' or '-r 
f:/python/a/', NameError is raised for the print in This was 
reported this SO question.

In both cases, the file is run with execfile(filename).

    def execfile(self, filename, source=None):
        "Execute an existing file"
        if source is None:
            with as fp:
                source =

My guess is that wrapping the source with f"__file__ = {filename}\n" and "del 
__file__\n" should work.

assignee: terry.reedy
components: IDLE
messages: 313140
nosy: terry.reedy
priority: normal
severity: normal
stage: needs patch
status: open
title: IDLE: set and unset __file__ for startup files
type: behavior
versions: Python 3.6, Python 3.7, Python 3.8

Python tracker <>
Python-bugs-list mailing list

Reply via email to