6

I do not necessarily want to stop python from "caching" its byte code, I just want to stop it from "crippling" all of my directories with a __pycache__ entry anywhere it finds and executes a script. For instance, I'd like the byte code of all of my scripts to be saved under, say $HOME/.python/cache.

I'm running Linux but I believe that would be interesting for Windows users as well.

paka
  • 791
  • 1
  • 8
  • 7
  • That will lead to conflicts very soon because python makes no difference between "your scripts" and "files from installed modules". And there will be lots of identical names if you include all folders of all installed 3rd party modules. My advise: Just ignore thes `__pycache__` folders. – MSeifert Aug 09 '17 at 10:06
  • @MSeifert It'll create conflicts only if one implements that feature without thinking. All "cached" bytecode files already have a suffix that matches the python version they were compiled for. Why not a prefix that matches the absolute location of the script, which *will* prevent clashes? That prefix can be a hash (like cached thumbnails), a full tree, whatever... –  Aug 09 '17 at 15:43

1 Answers1

2

TL;DR

No, you cannot move __pycache__.

Background

PEP 304 suggested the addition of an PYTHONBYTECODEBASE environment variable which would control where the bytecode is stored. It was withdrawn and never implemented, so what you want to do is not possible.

The move from one .pyc file per .py file to a single __pycache__ per folder, as per PEP 3147 was supposed to be a partial fix and is done in Python 3.

Stop __pycache__ from being created

You can stop python from creating any bytecode by passing the -B parameter to the python interpreter or by setting the PYTHONDONTWRITEBYTECODE environment variable. This is however not recommended as it may slow down your scripts.

Jonas Adler
  • 10,365
  • 5
  • 46
  • 73
  • Ah. Too bad it can't be done. From the quick number of up-votes I see I'm not the only one who'd have been interested with such a feature. Reading about the `-B` argument — I don't mind some of my scripts being slower — I suppose I can make it part of the she-bang in my scripts, right? –  Aug 09 '17 at 15:46
  • That's exactly what I have written in my post: «*I do* not *necessarily want to stop python from "caching" its byte code*» I mean I don't want to disable it *globally*. I can live with *some* directories containing a `__pycache__` just not *all* of them for as long as I can control which do — for as long as I can. –  Aug 09 '17 at 16:16