0

When I run my python script for the first time, I can find the cached bytecode file in the __pycache__ folder. When I make a few changes and run it again, I see the .pyc file isn't modified (even though the script runs as expected).

I guess the new bytecode must be generated somehow in memory.

Why isn't it modified? Is there a way I can find the modified file?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
mdmd111
  • 1
  • 1
  • 2
    `__pycache__` is only populated with `.pyc` files for *imported* files. If you are running your file as a script, the compiled code is indeed stored only in memory. What you are seeing may be left over from a run that imported your file as a module (a test runner, perhaps?). – chepner Feb 11 '22 at 15:56
  • 1
    Bytecode is _always_ stored in memory, whether or not it's also cached to disk or loaded from cache. There's nothing mysterious here, and Python is perfectly capable of running code without ever writing bytecode to disk at all (it does exactly that whenever you run code at the repl!). – Charles Duffy Feb 11 '22 at 15:57
  • I’m voting to close this question because it asks for something that doesn't exist (a "modified file" when content is never written to file at all). – Charles Duffy Feb 11 '22 at 15:58
  • 1
    BTW, CPython is the name of the Python executable implemented in C, the thing typically saved as `/usr/bin/python`; .pyc files aren't called "CPython files", they're just compiled bytecode (in a format that has nothing to do with C) cached to disk _by_ CPython. In theory, a non-CPython interpreter could also parse and execute that same bytecode, though I don't know if any have aimed for that level of compatibility in practice. – Charles Duffy Feb 11 '22 at 15:59
  • @chepner Thank you for your comment! In this case, I used the word script inaccurately, I didn't run it as a script. Anyway, if I run the file (not as a script) and import more files, should it be modified? – mdmd111 Feb 11 '22 at 16:18
  • If you run `python foo.py`, you will not get `__pycache__/foo.pyc`. If you run something that *imports* `foo.py` (say, `import foo`), then you will get an updated `__pycache__/foo.pyc` if `foo.py` is newer than an existing `__pycache__/foo.pyc`. – chepner Feb 11 '22 at 16:23
  • Whether or not `foo.py` imports other files has no bearing on whether `foo.pyc` will be generated. – chepner Feb 11 '22 at 16:23
  • @CharlesDuffy Thank you :) It makes much more sense now – mdmd111 Feb 11 '22 at 16:24
  • @chepner Thanks! – mdmd111 Feb 11 '22 at 16:31
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Feb 22 '22 at 07:54

0 Answers0