Like you & ctrl-alt-delor, I sought the mythical clean home directory. The call to readline.write_history_file is registered to run on exit in site.py (on my arch system, at /usr/lib/python3.9/site.py):
if readline.get_current_history_length() == 0:
# If no history was loaded, default to .python_history.
# The guard is necessary to avoid doubling history size at
# each interpreter exit when readline was already configured
# through a PYTHONSTARTUP hook, see:
# http://bugs.python.org/issue5845#msg198636
history = os.path.join(os.path.expanduser('~'),
'.python_history')
try:
readline.read_history_file(history)
except OSError:
pass
def write_history():
try:
readline.write_history_file(history)
except OSError:
# bpo-19891, bpo-41193: Home directory does not exist
# or is not writable, or the filesystem is read-only.
pass
atexit.register(write_history)
You can duplicate this in your PYTHONSTARUP but with a custom location for the python history. Here's mine (but if you like I'm sure you could used environment substitution to use the appropriate XDG directory.:
import os
import atexit
import readline
history = os.path.join(os.path.expanduser('~'), '.cache/python_history')
try:
readline.read_history_file(history)
except OSError:
pass
def write_history():
try:
readline.write_history_file(history)
except OSError:
pass
atexit.register(write_history)
You could overwrite the write_history_file function, but it's very hacky (you need it to ignore the argument it's given in lieu of your custom one), so I think this is the best solution. If this doesn't work, try creating a dummy entry in your custom python history file, so the history length is greater than 0.